Skip to content

Case Study: OpenAI ​

"Scaling a single Kubernetes cluster to this size is rarely done and requires some special care" — OpenAI, Scaling Kubernetes to 7,500 nodes (January 25, 2021)

Summary: OpenAI publishes unusually concrete engineering detail about three layers: the Kubernetes clusters that train models (2,500 nodes in 2018, 7,500 in 2021), the product data tier behind ChatGPT (one PostgreSQL primary plus nearly 50 read replicas in 2026), and its own outages (Redis-py data exposure in March 2023, the telemetry service outage in December 2024). The public API docs add the serving contract: streaming over SSE, rate limits in requests and tokens, a Batch API and prompt caching. Focus: Using the 4-step method (scope, estimate, high-level design, decisions) on only what OpenAI itself has published, with every other claim marked inference; training clusters and GPU scheduling; etcd and API server limits; PostgreSQL scaling and read replicas; the two postmortems; the serving API (SSE, rate limits, batch, prompt caching); moderation and system cards as safety constraints. Learning goal: Read a vendor's engineering posts the way a reviewer would: separate the quoted facts from your own guesses, map each subsystem to a generic chapter of this site, and re-implement one or two mechanisms (a two-budget rate limiter, a cache-miss lease, an SSE stream, gang admission, prefix-cache accounting) honestly, as teaching code and not as OpenAI's code.

This chapter closes the case-study group. It owns the worked reading of OpenAI's published material and the numbers; mechanics live in siblings: The 4-Step Approach for the method, Containers & Kubernetes for the cluster primitives, Rate Limiting, Real-Time Communication, Caching, Cascading Failures, Load Shedding, ML Systems, and Replication, Read Replicas & Failover.

How to read this page

Three labels are used everywhere. Cited means the sentence rests on a page we fetched, read and saved (the quote is at most 25 words and the source is in References). Inference means our own reasoning or a generic design; it may be wrong for OpenAI. Ours means code or numbers we wrote for teaching. OpenAI has not published the internals of ChatGPT's serving stack, its model-hosting scheduler, or its inference cost, so those parts are inference or simply absent.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
What can and cannot be known from public sourcesWhy it exists
Dated posts, 2018 to 2026Where it comes from
Step 1: what OpenAI says it runsScope
Step 2: the cited and estimated numbersEstimate
Training clusters on Kubernetes, 2,500 then 7,500 nodesTraining cluster
etcd, API servers, EndpointSlicesetcd and API servers
Pod networking, hub and spokeNetworking
Health checks, preflight, GPU scheduling, gangsGPU scheduling
Microsoft supercomputer, InfiniBandAzure supercomputer
ChatGPT product data tierPostgreSQL scaling
Redis cache, redis-pyRedis cache tier
API: streaming, rate limits, batch, cachingServing contract
Moderation, system cardsSafety
Two postmortemsIncidents
What to copyWhat you can copy
CodeGo, Laravel
Classic problemsSolving the classic problems
DecisionsChoosing
Monolith to distributedIn architecture
Hands-onLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

Which layer, which source.

LayerWhat OpenAI publishedWhereStatus
Training clustersKubernetes at 2,500 nodes (2018) and 7,500 nodes (2021): etcd, API servers, networking, GPU health, gang schedulingOpenAI blogCited
Product data tierOne PostgreSQL primary, nearly 50 read replicas, PgBouncer, cache locking, Azure Cosmos DB for shardable writesOpenAI blog, January 2026Cited
Serving contractSSE streaming, requests and tokens per minute, Batch API, prompt cachingPlatform docsCited
SafetyA free moderation endpoint, system cards published per modelPlatform docs, OpenAI blogCited
ReliabilityRedis-py data exposure (March 2023), telemetry service outage (December 2024)OpenAI blog, status pageCited
Inference engine, GPU placement for serving, request routingNot published in what we readnoneInference only
Training fabric (InfiniBand)Not stated in OpenAI's posts we fetched; Microsoft pages could not be fetchednoneInference only

The four steps applied.

StepQuestionOpenAI answer (cited unless marked)
ScopeWho are the users and what are the workloads?Research training jobs (MPI, GPUs); ChatGPT and API products with 800 million users
EstimateHow big?7,500 nodes; up to 70 GB heap per API server; millions of QPS on PostgreSQL; our token and cost arithmetic is inference
High-level designWhat are the boxes?Kubernetes per cluster, hub and spoke network, one PostgreSQL primary with replicas, Redis cache, Cosmos DB
DecisionsWhat trade-offs and failures?Single writer over sharding; no Kubernetes load balancing for training; staged rollouts after the December 2024 outage

Numbers to remember (all cited).

NumberMeaningSource
500 nodesWhere kubectl timeouts began (2018)2,500-node post
2 GBDefault etcd storage limit that stopped writes2,500-node post
5 API servers, 5 etcd nodesLargest cluster layout (2021)7,500-node post
70 GBHeap per API server at 7,500 nodes7,500-node post
1000xLoad reduction from EndpointSlices7,500-node post
Nearly 50Read replicas, several regionsPostgreSQL post
5,000Connection limit per Azure PostgreSQL instancePostgreSQL post
50 ms to 5 msAverage connection time with PgBouncerPostgreSQL post
1.2%ChatGPT Plus subscribers whose payment data may have been exposed in a nine-hour windowMarch 2023 post
3:16 PM to 7:38 PM PSTDecember 11, 2024 outage windowStatus page
50% and 24 hoursBatch API discount and completion windowBatch guide
1,024 tokensMinimum cacheable prompt length for GPT-5.6 and laterPrompt caching guide

Why it exists ​

System design interviews use invented companies. This chapter uses a real one whose engineers wrote down what broke. The value is the shape of the failures: etcd latency, a watch that fans out to every node, one primary that must not be overloaded, a cache whose connections get corrupted, a telemetry change that takes down the control plane.

The honest constraint: a company publishes the stories it chooses. A case study built from public posts is a set of facts with large gaps. The table shows what that means for you.

StyleWhat you getWhat you risk
Cited-only reading (this page)Facts you can checkGaps where the company is silent
Inference to fill the gapsA complete pictureConfident fiction; always label it
Copying the architectureFast startCopying a design built for a different workload

Analogy used through the page: an airport you can only see from the observation deck. You can read the runway layout and the incident reports the airport published; you cannot see the baggage system, so anything you say about it is a guess.

Three common misunderstandings, up front ​

  1. "OpenAI runs one giant cluster for everything." The 7,500-node post describes research training clusters, and says clusters never talk to each other so failures stay isolated. The December 2024 post says the company operates hundreds of Kubernetes clusters.
  2. "A famous company must have sharded its database." The January 2026 post says PostgreSQL stays unsharded with a single primary serving all writes, and gives the reasons.
  3. "Public docs describe how the model is served." The docs describe the contract (streaming, limits, batch, caching), not the GPU scheduling behind it.

Where it comes from ​

All dates below are the publication dates printed on the pages we read, except the docs, which are living pages we read on 2026-11-26.

2018-01-18  Scaling Kubernetes to 2,500 nodes     -> etcd on local SSD, Events in separate etcd, 2 GB limit
2021-01-25  Scaling Kubernetes to 7,500 nodes     -> hub and spoke, EndpointSlices, gang scheduling
2023-03-24  March 20 ChatGPT outage post          -> redis-py bug, 1.2% of Plus subscribers
2024-08-08  GPT-4o System Card                    -> red teaming, Preparedness scorecard
2024-12-11  API, ChatGPT and Sora outage          -> telemetry service, Kubernetes control plane
2026-01-22  Scaling PostgreSQL to 800M users      -> single primary, nearly 50 replicas
2026-11-26  Platform docs read today              -> SSE, rate limits, Batch API, prompt caching

What changed over time, as a table (cited from the posts above):

Concern201820212024 to 2026
Cluster sizeOver 2,500 nodes7,500 nodesHundreds of clusters (December 2024 post)
Pod networkFlannel, about 2 Gbit/s in pods vs 10 to 15 Gbit/s between machinesNative pod networking on Azure VMSS, host-level throughputNot covered in what we read
etcdLocal SSD, separate Events etcd5 etcd nodes, "no notable trouble"API server and DNS dependency named as the risk
SchedulingMostRequestedPriority to pack nodes for the autoscalerCoscheduling plugin for gangsNot covered
Data tierNot coveredNot coveredPostgreSQL single primary, nearly 50 replicas
Failure styleetcd limit cascades to autoscalerPrometheus OOM and WAL replayTelemetry change breaks control plane and DNS

The concept catalogue ​

The catalogue follows the 4-step approach: scope, estimate, then one block per subsystem (high-level design), then the decisions and failures. Each block says what is cited and what is inference.

Step 1, scope: two very different workloads Must-know ​

In plain words: OpenAI runs research jobs that occupy whole machines for days, and products that serve very many small requests. They need opposite designs, and the public posts cover them separately.

Common misunderstanding: "One architecture serves training and serving." The 7,500-node post says the company's workload is unusual: "a single pod occupies the entire node" for many jobs, with little HTTPS traffic and no need for A/B testing, blue/green or canaries. A product API needs exactly those things.

Definition: scoping means writing down functional and non-functional requirements before drawing boxes. For this case: training (throughput, GPU health, large job gangs) and serving (latency, availability, safety, cost).

Requirement          Training (cited, 2021)                 Serving (inference unless marked)
-----------------    -----------------------------------    ------------------------------------
Unit of work         MPI job across many whole nodes        One request, streamed tokens (cited API)
Failure cost         Any pod dies, job halts, restart       One request fails, client retries (cited)
Traffic shape        Spiky pod creation, hundreds at once   Many users; bursts after launches (cited: 10x write surge)
Load balancing       "very little HTTPS traffic"            Essential (inference)

Real scenario: a launch-day surge. The PostgreSQL post says write traffic grew by more than 10x when ChatGPT image generation went viral. A research cluster has no such external surge, but it has job-start spikes of hundreds of pods.

What provides it: the layering in Scaling Strategies and Latency Budgets.

Fix / how to use it: write the requirements table for your own system first; see the Go and Laravel sections for limits that follow from it.

Step 2, estimate: what the sources let you compute Must-know ​

In plain words: only a few numbers are public. Use them as anchors, and mark the arithmetic you add as your own.

Common misunderstanding: "If a number is in a blog post, derived numbers are facts too." A derived number inherits every assumption you made. Mark it.

Definition: a back-of-envelope estimate multiplies cited anchors by stated assumptions.

QuantityValueLabel
Users behind the PostgreSQL deployment800 millionCited (post title)
PostgreSQL QPSmillionsCited
Read replicasnearly 50Cited
Average QPS per replica if load were evenon the order of tens of thousands (for example 2,000,000 / 50 = 40,000)Inference (assumes 2 million total, even spread)
WAL streams the primary must serveone per replica, nearly 50Cited mechanism, count inferred from "primary must stream WAL to every replica"
Tokens per second at a 1,000,000 TPM limitabout 16,700Ours (1,000,000 / 60)
Cost of one cached read vs normal input0.1x at the rate quoted in the docsCited
back-of-envelope (ours)
1) 1,000,000 tokens per minute / 60 s        = ~16,667 tokens per second for one key
2) 1 write + 1 full read at 0.1x, 30m writes = 1.35x the ordinary input cost   (docs example)
3) 10 requests, 1 write + 9 reads            = 2.15x vs 10x with no caching     (docs example)

Cost of inference. OpenAI's posts we fetched give no per-request or per-GPU cost. Any figure you see is inference. A usable template is: cost per token = (GPU price per hour / tokens per second per GPU) / 3,600; every term except the price list in the docs is unknown. We therefore use the documented levers only: Batch API (50% lower cost, 24-hour window) and prompt caching.

Real scenario: a reviewer asks "how many replicas for 100 million users?" Answer with the ratio from the post (nearly 50 replicas for 800 million users, read-heavy), then say it is not a formula.

What provides it: Capacity Planning for method, The 4-Step Approach for the estimate step.

Fix / how to use it: keep a column called "label" in every estimate table; the Go code below computes the cache arithmetic so the doc examples can be checked.

Training cluster: Kubernetes at 2,500 then 7500 nodes Must-know ​

In plain words: OpenAI used ordinary Kubernetes for research jobs and pushed one cluster from 2,500 nodes (2018) to 7,500 nodes (2021). The 7500 nodes cluster ran the work behind models such as GPT-3, CLIP and DALL-E according to the post.

Common misunderstanding: "Kubernetes cannot run big training clusters." The post says the upside is "a simple infrastructure that allows our machine learning research teams to move faster", and it also says what makes this workable here: one pod per node for many jobs, so bin-packing and fragmentation are not common problems.

Definition: a training cluster is a set of GPU nodes where large jobs run as MPI groups; "If any of the participating pods die, the entire job halts and needs to be restarted", so jobs checkpoint and pods are called semi-stateful.

Job life cycle (cited, 2021)
1  submit job: hundreds of pods created at once        (spiky kube-scheduler load)
2  pods land one per node, MPI communicator forms
3  training runs, checkpoints regularly to blob storage
4  one pod dies -> whole job halts
5  restart from last checkpoint

Real scenario: a node gets a GPU Xid error at hour 30 of a run. The job stops, the node is cordoned by the health checks (see GPU scheduling), and the job resumes from a checkpoint.

PropertyCited valueWhy it matters
Pod placementOften a single pod on an entire nodeNo NUMA or PCIe contention for the scheduler to solve
NetworkFull bisection bandwidthNo rack or topology awareness needed
Service discoveryOne-time lookup at job startupKubernetes Services barely used
StorageMostly blob storage, few PersistentVolumesAvoids slow attach and detach

Fix / how to use it: if your jobs look like this, you can skip service meshes and ingress; see Containers & Kubernetes for the primitives. The gang package below models the admission rule.

The layout described in the 7,500-node post, as a picture:

Researcherskubectl, jobsHubroutes to spokesNAT hostservice CIDROne spoke: one Kubernetes cluster (clusters never talk to each other)5 API serversoutside the clusterup to 70 GB heap each5 etcd nodesdedicated nodesEvents in a separate etcdteam-resource-managerteam taints + webhookAbout 7,500 nodes, one pod per node for big jobsNVLink + GPUDirect inside the node, MPI between podshealth checks: passive, preflight taint, cron GPU testskubelet and node-exporterWATCH fan-out: use EndpointSlices

etcd limits and API servers Must-know ​

In plain words: Kubernetes keeps all cluster state in etcd and talks to it through API servers. At thousands of nodes, the load those two components see decides whether the cluster works.

Common misunderstanding: "If kubectl is slow, add API servers." In 2018, after passing 500 nodes, "our researchers started reporting regular timeouts from the kubectl command line tool"; adding Kube masters helped briefly, and past 10 replicas they knew they were "treating symptoms and not the cause".

Definition: etcd is a replicated key-value store that serializes writes with sequential disk I/O; its write latency bounds the control plane.

2018 etcd chain (cited)
1  >500 nodes: kubectl timeouts
2  more API servers: temporary relief
3  etcd write latency in the hundreds of ms on network SSD (P30, 5,000 IOPS, ~10% used)
4  move etcd to local SSD: latency 200 us
5  >1,000 nodes: apiserver reads >500 MB/s from etcd; Fluentd and Datadog list Events from every node
6  Events moved to their own etcd (--etcd-servers-overrides)
7  etcd hits its 2 GB default limit and stops writes
8  nodes fail health checks -> autoscaler tries to remove every worker
9  fixes: --quota-backend-bytes raised; autoscaler refuses to act on more than 50% of the cluster

Real scenarios: the etcd limit incident is a cascading failure: a store limit became a fleet-wide scale-down. In 2021, WATCHes on the kubelet Endpoints object grew as N squared and "occasionally 1GB/s or more"; EndpointSlices "brought this load down 1000x". The post's rule: be "very mindful of any API Server requests that scale with the size of the cluster".

Knob or factWhereValue or effect (cited)
--quota-backend-bytesetcdRaises the 2 GB default storage limit
--etcd-servers-overrideskube-apiserverSends /events to a separate etcd
--apiserver-countkube-apiserver (2018)Number of API servers, to keep Prometheus unconfused
5 API servers, 5 etcd2021 layoutRun outside the cluster on dedicated nodes
Heap per API server7,500 nodesUp to 70 GB
429 and 5xx ratesAlertsA high-level signal of API server trouble
Autoscaler sanity checkAutoscalerRefuses to terminate more than 50% of the cluster

What prevents it: separate Events etcd, local SSD, apiserver request budgets, smoothing node joins ("adding hundreds of nodes at once can overload API server capacity").

Fix / how to use it: the same approach appears in Containers & Kubernetes; the Lab section shows commands to check etcd size and API request rates (expected, not run).

Networking: from Flannel to native pod IPs Important ​

In plain words: pods need to talk fast. An overlay network that is fine for a web app capped the throughput of training jobs.

Common misunderstanding: "The CNI plugin is a detail." In 2018 pods using Flannel reached about 2 Gbit/s while machines reached 10 to 15 Gbit/s; in 2021 the post says "Flannel had difficulties scaling up the throughput required".

Definition: a CNI plugin gives each pod an IP. Native pod networking on Azure uses IP configurations on the VM scale set so pods get host-level throughput; no encapsulation. See Kubernetes Networking.

2021 network model (cited)
1  researchers connect to the hub
2  hub routes to any spoke (cluster) by native node/pod CIDR
3  spokes cannot reach each other (failure isolation)
4  a NAT host translates the service CIDR for outside traffic
ChoiceReason givenConsequence
Alias-based IPs, no route-based pod networkingAbout 200,000 IPs in use at once; route limitsSimple network, no MTU surprises
iptables mangle rules marking internet-in and internet-outPer-namespace bandwidth visibilityCounters exported by iptables-exporter
Hub and spokeIsolation, no cross-cluster dependenciesA researcher sees every cluster through the hub

Fix / how to use it: if you run throughput-bound pods, measure pod-to-pod bandwidth against host-to-host bandwidth before choosing a CNI.

Health checks, preflight and GPU scheduling Must-know ​

In plain words: at this size something is always broken. The cluster finds bad GPUs automatically, keeps them away from jobs, and schedules whole groups of pods or none.

Common misunderstanding: "Kubernetes schedules GPUs well out of the box." The post says Kubernetes by default does not prioritize fulfilling one StatefulSet over another: two experiments each wanting the whole cluster could each get half, "leading to a deadlock where neither experiment can make progress".

Definition: GPU scheduling here is: passive health checks, active GPU tests, taints for team quotas, balloon pods to keep nodes warm, and gang scheduling.

Node life cycle (cited)
1  node joins with a "preflight" taint and label
2  DaemonSet runs GPU tests; success removes the taint
3  node serves jobs; passive checks watch disks, network, GPU Xid errors (DCGM)
4  failing check -> node cordoned; serious failure -> eviction attempt
5  after pods end or 7 days (part of the SLA) the VM is terminated
6  CronJob runs the GPU tests again later on random nodes
MechanismDetail from the postPurpose
DCGM and dcgm-exporterDCGM_FI_DEV_XID_ERRORS metric into PrometheusDetect "Uncorrectable ECC error" and other Xid errors
Preflight taintAdded to every node at bootNo jobs on an untested GPU
team-resource-managerConfigMap of (node selector, team label, amount) plus admission webhookTeam capacity with borrowing through an "any" toleration
CPU and GPU balloonsLow-priority pods in a Deployment, max-size replicasKeep autoscaler from removing idle nodes; evicted instantly for real work
Coscheduling pluginScheduler plugin architecture, Kubernetes 1.18All pods of a gang or none
Priority policy (2018)MostRequestedPriority weight 1, InterPodAffinityPriority weight 2Pack nodes so unused ones can be terminated

Real scenario: the 2018 packing policy put 10+ copies of KubeDNS on some machines and exceeded "the ~200QPS that's allowed from each Azure VM"; an anti-affinity rule fixed it. A scheduling choice for batch work broke a shared service.

What provides it: Containers & Kubernetes (taints, tolerations, affinity), Chaos Engineering for deliberately testing node loss.

Fix / how to use it: the gang Go package below shows why pod-by-pod interleaving strands two jobs and all-or-nothing admission does not.

The Azure supercomputer and the fabric Good to know ​

In plain words: the clusters run on Microsoft Azure. The 2018 post says the largest cluster ran "in Azure on a combination of D15v2 and NC24 VMs", and the 2021 post mentions Azure VMSS and Azure-native pod networking.

Common misunderstanding: "The public blogs describe the supercomputer network." The OpenAI posts we read say nothing about InfiniBand; they say GPUs talk over NVLink and GPUDirect and that the clusters have "full bisection bandwidth". Microsoft announced a purpose-built Azure supercomputer for OpenAI, but the Microsoft pages could not be fetched from the machine used to write this chapter, so we do not cite figures from them.

Definition: a training cluster fabric connects GPUs inside a node (NVLink) and between nodes (a high-bandwidth network; in many GPU clouds this is InfiniBand). Inference: an InfiniBand-class network is the usual choice for MPI-style jobs, but whether it carries OpenAI's pod traffic is not in our sources.

ItemStatus
NVLink and GPUDirect inside nodesCited (7,500-node post)
Full bisection bandwidthCited
InfiniBand between nodesNot cited; inference only
Total GPU count of any clusterNot cited by OpenAI in the posts we read

Fix / how to use it: when you design a training cluster, ask for the network's bisection bandwidth in writing; see ML Systems.

PostgreSQL scaling and read replicas Must-know ​

In plain words: one database server takes every write; nearly 50 copies take the reads. The January 2026 post explains how that holds up for 800 million users.

Common misunderstanding: "At this scale you must shard." The post says "PostgreSQL can be scaled to reliably support much larger read-heavy workloads than many previously thought possible", and that sharding existing workloads would take "months or even years", so shardable write-heavy workloads move to Azure Cosmos DB and PostgreSQL stays unsharded.

Definition: single-primary with read replicas: one writer; replicas receive the write-ahead log (WAL) and serve reads; see Replication, Read Replicas & Failover.

Overload pattern (cited, PostgreSQL post)
1  upstream issue: cache miss storm, expensive joins, or write storm from a launch
2  database load rises, query latency rises
3  requests time out
4  retries amplify load -> vicious cycle, ChatGPT and API degrade
Problem named in the postSolution (cited)Our generic chapter
One writer cannot scale writesMove shardable write-heavy workloads to Cosmos DB; fix redundant writes; lazy writes; rate-limited backfillsSharding at System Level
Expensive queries (a 12-table join)Move join logic to the application; review ORM SQL; fix long idle queriesORM Pitfalls
Single point of failureHot standby in HA mode; critical reads on replicasReplication Topologies
Noisy neighbourLow and high priority tiers on separate instancesBulkheads
Connection limit (5,000 per instance)PgBouncer in transaction or statement modeConnection Pooling
Cache miss stormsCache locking and leasingCaching
WAL to every replicaCascading replication in testing, possibly over a hundred replicasReplication, Read Replicas & Failover
Retry storms, expensive query spikesRate limits at app, pooler, proxy and query layers; block a query digestLoad Shedding
Schema changes rewrite tablesLightweight changes only; 5-second timeout; concurrent index builds; no new tablesZero-Downtime Migrations

Real scenario: "we've had only one SEV-0 PostgreSQL incident" in 12 months, during the viral ChatGPT image generation launch when write traffic rose by more than 10x. Results quoted: low double-digit millisecond p99 client latency, five-nines availability.

What prevents it: every row above; the post says the MVCC write cost (the whole row is copied for each update) is why writes are the limit; see MVCC & VACUUM.

Fix / how to use it: the SQL snippet shows the schema-change rules (our table, not theirs); the cachelock package and the Laravel CachedProfile class implement the cache lease.

The data tier as the post describes it:

ApplicationChatGPT, APICache layerlock + lease on missPgBouncertransaction poolingpods per replicaRate limitsapp, pooler, proxy, queryOne primaryall writes, plus hotstandby for failoverAzure Cosmos DBshardable,write-heavy workloadsNearly 50 read replicas, several regionsprimary streams WAL to each; cascading replication in testingIsolation: low and high priority traffic on separate instancesschema changes: lightweight only, 5 second timeout, no new tablesWAL

The Redis cache tier and the redis-py data exposure Must-know ​

In plain words: ChatGPT cached user information in Redis. A bug in the Python client let one user's cached data come back for another user's request.

Common misunderstanding: "A cache bug only returns stale data." The March 2023 post says that in some cases "the corrupted data happens to match the data type the requester was expecting", so wrong-user data looks valid.

Definition: the bug sat in the redis-py asyncio client for Redis Cluster: requests and responses behave as two queues; if a request is cancelled after being pushed and before its response is popped, the pooled connection is left with an unread response.

redis-py failure sequence (cited)
1  request A pushed on the incoming queue
2  A is cancelled before its response is popped
3  connection returns to the shared pool
4  request B (other user) takes that connection
5  B pops A's response; type matches, so it looks valid

At 1 a.m. Pacific on March 20 a change to the server "caused a spike in Redis request cancellations". The post says some users saw other users' chat titles, and "1.2% of the ChatGPT Plus subscribers who were active during a specific nine-hour window" may have had payment-related information exposed (name, email, payment address, card type, last four digits, expiry; full card numbers were not exposed).

Action (cited)Class of fix
Patched the library and testedRoot cause
"Added redundant checks to ensure the data returned by our Redis cache matches the requesting user."Defence in depth
Examined logs, correlated data sources, notified usersIncident response
Improved logging and the robustness and scale of the Redis clusterDetection and capacity

Real scenario: any async pooled client: cancellation (timeouts, client disconnects) must not leave a half-used connection in the pool. This sits in Cascading Failures territory because the trigger was load, and in Secure SDLC & Incident Response for the data exposure handling.

Fix / how to use it: the Go cachelock test uses a value check; the practical rule is to store the owner id inside the cached value and compare it on read (inference, derived from the cited redundant check).

Request A (user 1)cancelledRequest B (user 2)gets the connection nextShared connection pool (asyncio)request queue in, response queue outA pushed, never popped its responseconnection recycled with data left behindRedis Clusteruser info cacheB reads A's cached user data if the type happens to matchmost mismatches only error out; the rare match looks valid

The serving contract: streaming, rate limits, batch, prompt caching Must-know ​

In plain words: the API tells you how to receive output as it is generated, how much you may send, how to run cheap bulk jobs, and how repeated prompts get cheaper.

Common misunderstanding: "The docs reveal how OpenAI serves models." They reveal the behaviour a client can rely on. Anything about GPUs, batching on the server or routing is inference.

Definition: four documented features:

FeatureWhat the docs say (cited)Design lesson
Streaming (SSE)stream=true returns server-sent events; "start printing or processing the beginning of the model's output while it continues generating"Time to first token matters more than total time; see Real-Time Communication
Rate limitsRPM, RPD, TPM, TPD, IPM; "Rate limits can be hit across any of the options depending on what occurs first"Limit on cost (tokens), not only calls; see Rate Limiting
Batch APIJSONL file, 50% lower cost, 24-hour completion window, queued-token limit separate from per-minute limits, 200 MB upload limitMove non-interactive work off the hot path
Prompt cachingReuse of a shared prompt prefix; minimum 1,024 tokens for GPT-5.6 and later; reads rounded down to a multiple of 128Put stable content first
Rate-limit response (cited headers)
1  client sends request
2  server charges requests and tokens
3  over budget -> HTTP 429, Retry-After header, x-ratelimit-* headers
4  client waits at least Retry-After plus a small random delay
5  traffic above 1M TPM should grow at most 50% per 15 minutes (docs rule of thumb)
Header (cited)Meaning
Retry-AfterMinimum seconds to wait on a temporary 429 or 503
x-ratelimit-limit-requests, x-ratelimit-limit-tokensBudget
x-ratelimit-remaining-requests, x-ratelimit-remaining-tokensWhat is left
x-ratelimit-reset-requests, x-ratelimit-reset-tokensWhen it refills
x-ratelimit-limit-project-tokens and project variantsProject-scoped token limit

Idempotency. The API guides we fetched (streaming, rate limits, batch, prompt caching, moderation) contain no idempotency header, so we do not claim one. What they do say is that official SDKs retry eligible 429 and 503 responses. A retrying client of any non-idempotent call needs its own key discipline; see API Idempotency and REST API Design. This is inference about client design, not an OpenAI claim.

Real scenarios: a chat UI streams deltas; a nightly evaluation uses the Batch API; an agent reuses a long system prompt and tool list at the front so prompt caching hits; a client honours Retry-After and adds jitter (Timeouts, Retries & Jitter).

Cost and caching arithmetic (cited example): at the 0.1x read rate with 30-minute writes, writing a prefix once and reusing it once costs 1.35x its ordinary input cost, against 2x for processing it twice; across ten requests one write and nine reads cost 2.15x against 10x.

Fix / how to use it: Go: ratelimit (two budgets and headers), sse (stream), prefixcache (prefix accounting). Laravel: TokenRateLimit middleware and ChatStreamController.

Safety systems: moderation endpoint and system cards Important ​

In plain words: OpenAI publishes a free classifier endpoint you can call, and a system card with each model describing the risks they tested and the mitigations.

Common misunderstanding: "Safety is a filter bolted on at the end." The GPT-4o System Card says "We thoroughly evaluate new models for potential risks and build in appropriate safeguards before deploying them in ChatGPT or the API", and describes external red teaming (more than 100 external red teamers, 45 languages) and a Preparedness Framework scorecard. Safety is a release gate, which in system design terms is a non-functional requirement with a deployment check.

Definition: the moderation endpoint classifies text and images; "The moderation endpoint is free to use, and image files can be up to 20 MB". It can run standalone or alongside a response; the application decides what to do (filter, route, block).

MechanismCited factsAs a design constraint
Moderation endpointModel omni-moderation-latest, text and image input, freeAdd a pre-check or post-check hop with its own timeout and fallback (inference)
System cardPublished per model; includes red teaming, evaluations, scorecardRelease gate and documentation artefact
Preparedness scorecardCategories scored; GPT-4o voice scored low in three of four, persuasion borderline mediumA numbered threshold before launch

Real scenario (inference): a chat product screens user input and model output with the moderation endpoint; on a classifier timeout it must choose between failing open and failing closed, which is a product decision, not a technical one.

Fix / how to use it: keep safety checks asynchronous only when the risk allows; link to Graceful Degradation.

Reliability: the December 2024 telemetry service outage Must-know ​

In plain words: a monitoring change meant to make things safer took everything down, because it overloaded the Kubernetes control plane.

Common misunderstanding: "The data plane keeps serving if the control plane dies." The postmortem says the data plane "is designed to operate independently of the control plane", but "the Kubernetes API server is required for DNS resolution", and DNS-based service discovery failed.

Definition: an incident postmortem lists impact, root cause, why it was not caught, why recovery was slow, a timeline and prevention.

December 11, 2024 (PST, cited)
1  2:23 PM  change merged, pipeline starts
2  3:12 PM  new telemetry service deployed (applied to all clusters 2:51 to 3:20)
3  3:13 PM  alerts fire
4  3:16 PM  customer impact begins; root cause identified
5  3:27 PM  traffic moved away from impacted clusters
6  3:40 PM  maximum customer impact
7  4:36 PM  first cluster recovered
8  7:38 PM  all clusters recovered
Why (cited)Detail
Root causeTelemetry configuration made every node run resource-intensive Kubernetes API operations whose cost scaled with cluster size
Not caughtStaging cluster showed no issue; impact only in large clusters; evaluated CPU and memory, not API server load
Delayed visibility"DNS caching mitigated the impact temporarily" for about 20 minutes while the rollout continued
Slow recoveryFixing needed access to the API servers that were overwhelmed
Mitigations usedScale down cluster size, block network access to admin APIs, scale up API servers

Prevention list in the post: phased rollouts with monitoring for all infrastructure config changes; fault injection tests; emergency control plane access ("We do not yet have a mechanism to ensure access to the API server"); decoupling the data plane from the control plane. See Chaos Engineering, Observability and Cascading Failures.

Real scenario: the 2021 post warned about this class: "very mindful of any API Server requests that scale with the size of the cluster". The 2024 outage is that warning, realised by a telemetry agent (the connection is our inference; the posts do not link them).

Fix / how to use it: roll out agents that touch the control plane one cluster at a time, and test at the production size.

Deploynew telemetryservice, 3:12 PMEvery noderuns API callscost scales with sizeAPI serversoverwhelmed,control plane downDNS cachesexpire over about20 minutesServicescannot findeach otherWhy it was not caughtstaging cluster too small to show itDNS cache delayed visible failurerollout continued meanwhileWhy recovery was slowthe fix (remove the service) needs the APIscale clusters down, block admin APIs,scale API servers up; 3:16 PM to 7:38 PM

Observability Important ​

In plain words: watch what the platform itself costs the control plane.

Common misunderstanding: "More telemetry is always safer." The December 2024 incident was a telemetry rollout; the 2021 post says Prometheus ran out of memory and took hours to replay its WAL, so they "drop" metrics they never read.

Definition (cited): Prometheus and Grafana with kube-prometheus; alert on the rate of HTTP 429 and 5xx at the API servers; iptables-exporter for per-namespace traffic; dcgm-exporter for GPU errors; a Grafana /api/v1/series query with {le!=""} made Prometheus memory grow unbounded, fixed by a context timeout patch; GOMAXPROCS=24 improved WAL replay.

SignalSource (cited)Question answered
API server 429 and 5xxGrafana dashboardsIs the control plane overloaded?
DCGM_FI_DEV_XID_ERRORSdcgm-exporterIs a GPU failing?
Internet in and out per namespaceiptables mangle countersWho is using bandwidth?
Nodes and pending podsDashboardsIs a job start stuck?

The 2021 post lists as unsolved: Prometheus storage compaction and WAL replay, and pod network traffic shaping. See Observability.

Fix / how to use it: budget telemetry load like any other workload.

What you can copy ​

OpenAI subsystemThe generic ideaChapterCopy when
Separate Events etcdIsolate a noisy write stream from the core storeContainers & KubernetesYour cluster has more than a few hundred nodes
Gang schedulingAll-or-nothing admissionContainers & KubernetesJobs need every member to start
Single primary + replicasScale reads first, move shardable writes outReplication TopologiesRead-heavy, hard to shard
PgBouncer per replicaPooling near the databaseConnection PoolingConnection limits hurt
Cache leaseOne refill per keyCachingCache miss storms
Token and request budgetsLimit on cost, not on callsRate LimitingCalls vary in size
Batch APIAsync bulk lane at lower priceServerless & Event-Driven ComputeWork is not interactive
Phased rolloutsLimit blast radiusChaos EngineeringAny fleet-wide change
System cardDocumented release gateSecure SDLC & Incident ResponseYou ship models

What not to copy: the 7,500-node hub and spoke is built for researchers; a product API needs load balancing and canaries that the training clusters do not.

Mechanics ​

Knobs and limits named in the sources ​

KnobComponentValue or note
--quota-backend-bytesetcdRaise from the 2 GB default
--etcd-servers-overrideskube-apiserver/events#https://... to a separate etcd
--serialize-image-pullskubeletDefault true; set false (needs overlay2)
--image-pull-progress-deadlinekubeletSet to 30 minutes in 2018
max-concurrent-downloadsDocker daemonSet to 10
GOMAXPROCSPrometheus24 improved WAL replay
Pod Disruption BudgetPodDecides if an eviction is allowed
Taint openai.com/team=teamname:NoScheduleNodesTeam quota
Connection limitAzure PostgreSQL5,000 per instance
Schema change timeoutPostgreSQL deployment5 seconds
prompt_cache_keyResponses APIRequest field named in the caching guide
completion_windowBatch APIOnly 24h

Errors and messages ​

Message or codeContextMeaning
rpc error: code = 2 desc = net/http: request canceled2018 image pullsPull taking too long without progress
HTTP 429APIRate limit or slow_down ramp limit
HTTP 503 server_is_overloadedAPIModel overload; use Retry-After
query processing would load too many samplesPrometheusQuery too wide for storage
Uncorrectable ECC error (Xid)GPUHardware fault; reset or replace

Limits and defaults ​

ItemValueSource
Batch input filewell below 200 MBBatch guide
Moderation imageup to 20 MBModeration guide
Cache breakpoints per requestup to four writesPrompt caching guide
Ramp ruleat most 50% every 15 minutes above 1M TPMRate-limit guide

Go ​

Example ​

Five small packages, stdlib only, tested. They re-implement mechanisms named above; none is OpenAI code.

The two-budget limiter returns x-ratelimit-* style headers and a Retry-After, and the client delay treats the server hint as a minimum:

go
// Package ratelimit is a teaching re-implementation of a two-budget limiter
// (requests per minute and tokens per minute) that reports its state in
// headers shaped like the ones documented on the OpenAI platform rate-limit
// page. It is not OpenAI's implementation.
package ratelimit

import (
	"math"
	"net/http"
	"strconv"
	"sync"
	"time"
)

// Limiter holds two token buckets that refill continuously.
type Limiter struct {
	mu       sync.Mutex
	now      func() time.Time
	rpm, tpm float64
	reqs     float64
	toks     float64
	last     time.Time
}

// New creates a limiter with a per-minute request budget and token budget.
func New(rpm, tpm int, now func() time.Time) *Limiter {
	if now == nil {
		now = time.Now
	}
	return &Limiter{now: now, rpm: float64(rpm), tpm: float64(tpm),
		reqs: float64(rpm), toks: float64(tpm), last: now()}
}

// Decision is the outcome of Allow.
type Decision struct {
	OK         bool
	RetryAfter time.Duration
	Remaining  struct{ Requests, Tokens int }
}

func (l *Limiter) refill() {
	n := l.now()
	el := n.Sub(l.last).Minutes()
	l.last = n
	l.reqs = math.Min(l.rpm, l.reqs+el*l.rpm)
	l.toks = math.Min(l.tpm, l.toks+el*l.tpm)
}

// Allow charges one request and an estimated token cost. Either budget can
// reject the call; whichever runs out first wins, as the OpenAI docs describe.
func (l *Limiter) Allow(estTokens int) Decision {
	l.mu.Lock()
	defer l.mu.Unlock()
	l.refill()
	var d Decision
	need := float64(estTokens)
	if l.reqs >= 1 && l.toks >= need {
		l.reqs--
		l.toks -= need
		d.OK = true
	} else {
		waitReq := math.Max(0, (1-l.reqs)/l.rpm)
		waitTok := math.Max(0, (need-l.toks)/l.tpm)
		d.RetryAfter = time.Duration(math.Max(waitReq, waitTok) * float64(time.Minute))
	}
	d.Remaining.Requests = int(l.reqs)
	d.Remaining.Tokens = int(l.toks)
	return d
}

// SetHeaders writes x-ratelimit-* style headers and Retry-After on rejection.
func (l *Limiter) SetHeaders(h http.Header, d Decision) {
	h.Set("x-ratelimit-limit-requests", strconv.Itoa(int(l.rpm)))
	h.Set("x-ratelimit-limit-tokens", strconv.Itoa(int(l.tpm)))
	h.Set("x-ratelimit-remaining-requests", strconv.Itoa(d.Remaining.Requests))
	h.Set("x-ratelimit-remaining-tokens", strconv.Itoa(d.Remaining.Tokens))
	if !d.OK {
		secs := int(math.Ceil(d.RetryAfter.Seconds()))
		if secs < 1 {
			secs = 1
		}
		h.Set("Retry-After", strconv.Itoa(secs))
	}
}

// BackoffDelay returns how long a client should wait: the server hint is a
// minimum, jitter in [0,1) is added on top, as the docs advise.
func BackoffDelay(retryAfter string, attempt int, base time.Duration, jitter float64) time.Duration {
	if secs, err := strconv.Atoi(retryAfter); err == nil && secs >= 0 {
		return time.Duration(secs)*time.Second + time.Duration(jitter*float64(time.Second))
	}
	d := base << uint(attempt)
	return d + time.Duration(jitter*float64(d))
}
go
package ratelimit

import (
	"net/http"
	"testing"
	"time"
)

func TestTokenBudgetRunsOutBeforeRequestBudget(t *testing.T) {
	clock := time.Unix(0, 0)
	l := New(100, 1000, func() time.Time { return clock })
	if d := l.Allow(900); !d.OK {
		t.Fatal("first call should pass")
	}
	d := l.Allow(900) // 99 requests left, only 100 tokens left
	if d.OK {
		t.Fatal("token budget should reject")
	}
	if d.RetryAfter <= 0 {
		t.Fatal("expected a retry hint")
	}
	h := http.Header{}
	l.SetHeaders(h, d)
	if h.Get("Retry-After") == "" || h.Get("x-ratelimit-remaining-tokens") != "100" {
		t.Fatalf("bad headers: %v", h)
	}
}

func TestRefillAllowsAfterWaiting(t *testing.T) {
	clock := time.Unix(0, 0)
	l := New(60, 600, func() time.Time { return clock })
	l.Allow(600)
	if l.Allow(10).OK {
		t.Fatal("should be empty")
	}
	clock = clock.Add(30 * time.Second) // half a minute refills 300 tokens
	if !l.Allow(10).OK {
		t.Fatal("should pass after refill")
	}
}

func TestBackoffHonoursRetryAfterAsMinimum(t *testing.T) {
	got := BackoffDelay("3", 5, time.Second, 0.5)
	if got < 3*time.Second {
		t.Fatalf("delay %v below server hint", got)
	}
	if BackoffDelay("", 2, time.Second, 0) != 4*time.Second {
		t.Fatal("fallback should be exponential")
	}
}

The cache lease: 200 concurrent misses cause one database read.

go
// Package cachelock shows the "only one reader refills a missed key" idea the
// OpenAI PostgreSQL post describes as cache locking and leasing. It is a small
// single-process model, not OpenAI's code.
package cachelock

import (
	"sync"
	"sync/atomic"
)

type call struct {
	wg  sync.WaitGroup
	val string
	err error
}

// Cache is a map cache with a per-key lease on misses.
type Cache struct {
	mu     sync.Mutex
	data   map[string]string
	flight map[string]*call
	Loads  atomic.Int64 // how many times the backing store was hit
}

func New() *Cache {
	return &Cache{data: map[string]string{}, flight: map[string]*call{}}
}

// Get returns the cached value. On a miss exactly one caller runs load; the
// others wait for that result instead of hitting the database.
func (c *Cache) Get(key string, load func() (string, error)) (string, error) {
	c.mu.Lock()
	if v, ok := c.data[key]; ok {
		c.mu.Unlock()
		return v, nil
	}
	if f, ok := c.flight[key]; ok {
		c.mu.Unlock()
		f.wg.Wait()
		return f.val, f.err
	}
	f := &call{}
	f.wg.Add(1)
	c.flight[key] = f
	c.mu.Unlock()

	c.Loads.Add(1)
	f.val, f.err = load()

	c.mu.Lock()
	if f.err == nil {
		c.data[key] = f.val
	}
	delete(c.flight, key)
	c.mu.Unlock()
	f.wg.Done()
	return f.val, f.err
}

// Invalidate drops a key, simulating a cache-layer failure for one key.
func (c *Cache) Invalidate(key string) {
	c.mu.Lock()
	delete(c.data, key)
	c.mu.Unlock()
}
go
package cachelock

import (
	"sync"
	"testing"
	"time"
)

func TestMissStormLoadsOnce(t *testing.T) {
	c := New()
	var wg sync.WaitGroup
	for i := 0; i < 200; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			v, err := c.Get("user:1", func() (string, error) {
				time.Sleep(20 * time.Millisecond)
				return "row", nil
			})
			if err != nil || v != "row" {
				t.Error("bad result")
			}
		}()
	}
	wg.Wait()
	if got := c.Loads.Load(); got != 1 {
		t.Fatalf("expected 1 database read, got %d", got)
	}
}

func TestInvalidateThenReload(t *testing.T) {
	c := New()
	load := func() (string, error) { return "x", nil }
	c.Get("k", load)
	c.Invalidate("k")
	c.Get("k", load)
	if c.Loads.Load() != 2 {
		t.Fatal("expected a second load after invalidation")
	}
}

SSE writer and reader with the event names from the OpenAI streaming guide (our server):

go
// Package sse writes and reads Server-Sent Events frames. The wire format is
// the WHATWG one (data lines, blank line terminator); the event names in the
// tests mimic the style used in the OpenAI streaming guide but the server
// here is ours.
package sse

import (
	"bufio"
	"fmt"
	"io"
	"net/http"
	"strings"
)

// Event is one SSE frame.
type Event struct {
	Name string
	Data string
}

// Handler streams the given tokens as response.output_text.delta events and
// ends with response.completed. It flushes after every frame.
func Handler(tokens []string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		fl, ok := w.(http.Flusher)
		if !ok {
			http.Error(w, "streaming unsupported", http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "text/event-stream")
		w.Header().Set("Cache-Control", "no-cache")
		for _, t := range tokens {
			select {
			case <-r.Context().Done(): // client went away: stop generating
				return
			default:
			}
			fmt.Fprintf(w, "event: response.output_text.delta\ndata: %s\n\n", t)
			fl.Flush()
		}
		fmt.Fprint(w, "event: response.completed\ndata: {}\n\n")
		fl.Flush()
	}
}

// Read parses frames until EOF and sends each on the callback.
func Read(r io.Reader, fn func(Event)) error {
	sc := bufio.NewScanner(r)
	var ev Event
	var data []string
	flush := func() {
		if ev.Name != "" || len(data) > 0 {
			ev.Data = strings.Join(data, "\n")
			fn(ev)
		}
		ev, data = Event{}, nil
	}
	for sc.Scan() {
		line := sc.Text()
		switch {
		case line == "":
			flush()
		case strings.HasPrefix(line, "event:"):
			ev.Name = strings.TrimSpace(strings.TrimPrefix(line, "event:"))
		case strings.HasPrefix(line, "data:"):
			data = append(data, strings.TrimPrefix(strings.TrimPrefix(line, "data:"), " "))
		}
	}
	flush()
	return sc.Err()
}
go
package sse

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestStreamRoundTrip(t *testing.T) {
	srv := httptest.NewServer(Handler([]string{"Hel", "lo"}))
	defer srv.Close()
	resp, err := http.Get(srv.URL)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	if ct := resp.Header.Get("Content-Type"); ct != "text/event-stream" {
		t.Fatalf("content type %q", ct)
	}
	var text strings.Builder
	var last string
	err = Read(resp.Body, func(e Event) {
		last = e.Name
		if e.Name == "response.output_text.delta" {
			text.WriteString(e.Data)
		}
	})
	if err != nil || text.String() != "Hello" || last != "response.completed" {
		t.Fatalf("text=%q last=%q err=%v", text.String(), last, err)
	}
}

Gang admission versus pod-by-pod interleaving, and prefix-cache accounting with the documented 1,024 and 128 constants:

go
// Package gang models all-or-nothing admission for jobs made of many pods, the
// problem the OpenAI 7,500-node post solves with the Coscheduling plugin. This
// is a toy admission check, not the Kubernetes scheduler plugin.
package gang

import "errors"

var ErrNoCapacity = errors.New("gang does not fit; nothing placed")

// Job needs Pods whole nodes (one pod per node, as in the post's workload).
type Job struct {
	Name string
	Pods int
}

// Cluster tracks free nodes.
type Cluster struct{ Free int }

// PlaceOne places a single pod of a job if a node is free (the default,
// non-gang behaviour: pods of different jobs interleave).
func (c *Cluster) PlaceOne() bool {
	if c.Free == 0 {
		return false
	}
	c.Free--
	return true
}

// Gang admits the whole job or none of it.
func (c *Cluster) Gang(j Job) error {
	if j.Pods > c.Free {
		return ErrNoCapacity
	}
	c.Free -= j.Pods
	return nil
}
go
package gang

import "testing"

func TestPodByPodInterleavingStrandsBothJobs(t *testing.T) {
	c := &Cluster{Free: 100}
	a, b := Job{"a", 100}, Job{"b", 100}
	pa, pb := 0, 0
	for i := 0; i < 100; i++ { // the scheduler alternates between the two queues
		if i%2 == 0 && c.PlaceOne() {
			pa++
		} else if c.PlaceOne() {
			pb++
		}
	}
	if pa >= a.Pods || pb >= b.Pods || c.Free != 0 {
		t.Fatalf("expected both jobs stranded, got %d and %d", pa, pb)
	}
}

func TestGangAdmitsWholeOrNone(t *testing.T) {
	c := &Cluster{Free: 100}
	if err := c.Gang(Job{"a", 100}); err != nil {
		t.Fatal(err)
	}
	if err := c.Gang(Job{"b", 100}); err != ErrNoCapacity {
		t.Fatalf("want ErrNoCapacity, got %v", err)
	}
	if c.Free != 0 {
		t.Fatal("a failed gang must not take nodes")
	}
}
go
// Package prefixcache is a model of prompt-prefix caching accounting. The
// constants (1,024 minimum, reads rounded down to a multiple of 128) are the
// ones the OpenAI prompt caching guide states for GPT-5.6 and later; the
// matching logic is ours and works on whole tokens, not hidden state.
package prefixcache

const (
	MinCacheable = 1024
	Granule      = 128
)

// Cache remembers the longest token prefix it has seen.
type Cache struct{ seen [][]int }

// Request processes a prompt and returns how many tokens were read from cache.
func (c *Cache) Request(prompt []int) (cached int) {
	best := 0
	for _, s := range c.seen {
		n := 0
		for n < len(s) && n < len(prompt) && s[n] == prompt[n] {
			n++
		}
		if n > best {
			best = n
		}
	}
	if best >= MinCacheable {
		cached = best / Granule * Granule
	}
	if len(prompt) >= MinCacheable {
		c.seen = append(c.seen, append([]int(nil), prompt...))
	}
	return cached
}
go
package prefixcache

import "testing"

func seq(n, off int) []int {
	s := make([]int, n)
	for i := range s {
		s[i] = i + off
	}
	return s
}

func TestSharedPrefixIsReadInGranules(t *testing.T) {
	var c Cache
	if c.Request(seq(1500, 0)) != 0 {
		t.Fatal("first request writes, reads nothing")
	}
	p := append(seq(1300, 0), seq(100, 9000)...) // shares 1300 tokens
	if got := c.Request(p); got != 1280 {
		t.Fatalf("want 1280 (1300 rounded down to 128), got %d", got)
	}
}

func TestShortPromptsAreNeverCached(t *testing.T) {
	var c Cache
	c.Request(seq(500, 0))
	if c.Request(seq(500, 0)) != 0 {
		t.Fatal("below 1,024 tokens nothing is cached")
	}
}

func TestChangeAtTheFrontKillsTheCache(t *testing.T) {
	var c Cache
	c.Request(seq(2000, 0))
	if c.Request(seq(2000, 1)) != 0 {
		t.Fatal("a different first token means no shared prefix")
	}
}

SQL for the schema-change rules and a replica-side read:

sql
-- Our own illustration of two rules from OpenAI's PostgreSQL post:
-- only lightweight schema changes, with a 5-second timeout, and indexes
-- created concurrently. The table itself is invented for the lab.
CREATE TABLE usage_ledger (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    api_key_id  bigint      NOT NULL,
    model       text        NOT NULL,
    input_tokens  integer   NOT NULL CHECK (input_tokens >= 0),
    cached_tokens integer   NOT NULL DEFAULT 0 CHECK (cached_tokens >= 0),
    output_tokens integer   NOT NULL CHECK (output_tokens >= 0),
    created_at  timestamptz NOT NULL DEFAULT now()
);

-- Lightweight change: adding a nullable column does not rewrite the table.
SET lock_timeout = '5s';
ALTER TABLE usage_ledger ADD COLUMN batch_id text;

-- Not allowed by the rule: a type change forces a full table rewrite.
-- ALTER TABLE usage_ledger ALTER COLUMN input_tokens TYPE bigint;

-- Allowed: concurrent index build (cannot run inside a transaction block).
CREATE INDEX CONCURRENTLY usage_ledger_key_time
    ON usage_ledger (api_key_id, created_at DESC);

-- Read path that belongs on a replica: tokens per key per minute.
SELECT api_key_id, date_trunc('minute', created_at) AS minute,
       sum(input_tokens - cached_tokens) AS billable_input
FROM usage_ledger
WHERE created_at >= now() - interval '1 hour'
GROUP BY 1, 2;

The lightweight-change rule in two statements (ours; the post states the rule, not this SQL):

sql
SET lock_timeout = '5s';
ALTER TABLE usage_ledger ADD COLUMN batch_id text;  -- no table rewrite

The Go angle ​

  • net/http with an http.Flusher is all SSE needs; always watch r.Context().Done() so a closed client stops generation.
  • A sync.WaitGroup per in-flight key is a small single-flight; the standard extended library has golang.org/x/sync/singleflight for the same idea.
  • Use time.Duration arithmetic in one place for Retry-After plus jitter; the official OpenAI Go SDK is the client to use against the real API, and its retry behaviour is documented as SDK-dependent.
  • Test time with an injected clock (as the limiter does) rather than sleeping.

Laravel ​

Example ​

A middleware that charges a request and an estimated token cost against Laravel 13's RateLimiter::increment (its amount argument is in the rate-limiting docs) and writes the headers:

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Symfony\Component\HttpFoundation\Response;

/**
 * Two budgets per API key (requests and estimated tokens per minute), reported
 * in x-ratelimit-* headers. A teaching sketch of the behaviour documented on
 * the OpenAI platform rate-limit page; not OpenAI's code.
 */
class TokenRateLimit
{
    public function __construct(
        private int $rpm = 500,
        private int $tpm = 200_000,
    ) {
    }

    public function handle(Request $request, Closure $next): Response
    {
        $key = 'key:' . ($request->bearerToken() ?? $request->ip());
        $estimate = (int) ceil(strlen((string) $request->getContent()) / 4);

        // Laravel 13 RateLimiter::increment accepts an amount (rate-limiting docs).
        $reqs = RateLimiter::increment("$key:rpm", 60, 1);
        $toks = RateLimiter::increment("$key:tpm", 60, max($estimate, 1));

        if ($reqs > $this->rpm || $toks > $this->tpm) {
            $retry = max(
                RateLimiter::availableIn("$key:rpm"),
                RateLimiter::availableIn("$key:tpm"),
            );

            return response()->json(['error' => ['type' => 'rate_limit_error']], 429)
                ->withHeaders([
                    'Retry-After' => (string) max($retry, 1),
                    'x-ratelimit-limit-requests' => (string) $this->rpm,
                    'x-ratelimit-limit-tokens' => (string) $this->tpm,
                    'x-ratelimit-remaining-requests' => '0',
                    'x-ratelimit-remaining-tokens' => (string) max($this->tpm - $toks, 0),
                ]);
        }

        $response = $next($request);
        $response->headers->set('x-ratelimit-remaining-requests', (string) ($this->rpm - $reqs));
        $response->headers->set('x-ratelimit-remaining-tokens', (string) ($this->tpm - $toks));

        return $response;
    }
}

A cache-miss lease with Cache::lock(...)->block() and a replica connection, as in the cache-miss problem from the PostgreSQL post:

php
<?php

namespace App\Services;

use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * Cache-miss protection: one request refills a missed key, the rest wait for
 * it. Same idea as the cache locking and leasing described in OpenAI's
 * PostgreSQL scaling post, built from Laravel's documented Cache::lock.
 */
class CachedProfile
{
    public function find(int $id): ?array
    {
        $key = "profile:$id";

        if (($hit = Cache::get($key)) !== null) {
            return $hit;
        }

        $lock = Cache::lock("lock:$key", 10);

        try {
            // Followers block up to 3 seconds for the leader to fill the cache.
            $lock->block(3);

            return Cache::remember($key, 300, function () use ($id) {
                $row = DB::connection('replica')->table('profiles')->find($id);

                return $row ? (array) $row : null;
            });
        } catch (LockTimeoutException) {
            // Waited too long: degrade instead of stampeding the database.
            return null;
        } finally {
            $lock->release();
        }
    }
}

Server-sent events with response()->eventStream() and Illuminate\Http\StreamedEvent:

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\StreamedEvent;

/**
 * Streams tokens to a browser as server-sent events with Laravel's documented
 * response()->eventStream(). The generator stands in for an upstream model
 * stream; the event names copy the style of the OpenAI streaming guide.
 */
class ChatStreamController
{
    public function __invoke(Request $request)
    {
        return response()->eventStream(function () {
            foreach (['Hel', 'lo', ' world'] as $token) {
                yield new StreamedEvent(event: 'response.output_text.delta', data: $token);
            }
            yield new StreamedEvent(event: 'response.completed', data: '{}');
        });
    }
}

The Laravel angle ​

  • response()->eventStream() and StreamedEvent are documented in the Laravel 13 responses docs; the JavaScript side can use the @laravel/stream-react or @laravel/stream-vue packages named there.
  • RateLimiter::increment($key, $decaySeconds, $amount) is atomic on the Redis, Memcached and database cache stores (rate-limiting docs); it is a fixed-window counter, not a token bucket, so bursts at window edges are allowed.
  • Cache::lock('name', 10) and ->block(5) are in the cache docs; Cache::flexible implements stale-while-revalidate and is another way to avoid refill stampedes.
  • Http::retry(3, 100) retries with a fixed delay; for 429 with Retry-After pass a closure that returns the header value in milliseconds.
  • Under Octane or PHP-FPM, an SSE response holds a worker for its whole life; size workers for streams, or use Reverb for fan-out (see the real-time chapter).

Solving the classic problems ​

ProblemSolutionHowCost or limit
kubectl timeouts at scaleFix etcd firstLocal SSD, separate Events etcdMore etcd clusters to run
Fleet-wide scale-down after storage limitAutoscaler sanity checkRefuse more than 50% terminationSlower legitimate scale-down
Watch fan-outEndpointSlicesAvoid N squared watch payloadsNeeds Kubernetes 1.17 or later
Half-scheduled jobsGang schedulingCoscheduling pluginPlugin to maintain
Single writer saturatesOffload reads, shard writes elsewhereReplicas, Cosmos DBTwo data systems
Miss stormLock and leaseOne reader refillsWaiters add latency
Retry stormLayered rate limits, jittered retriesApp, pooler, proxy, querySome requests rejected
Wrong-user cache dataVerify owner on readRedundant checkSmall CPU cost
Control plane overloadPhased rollout and break-glass accessOne cluster at a timeSlower rollouts

Retry storm on a limited API ​

Follow Retry-After as a minimum and add jitter; stop after a bounded number of attempts and a total deadline (the docs give both rules). The Go BackoffDelay function and Laravel Http::retry closure implement it. See Timeouts, Retries & Jitter.

Cache miss storm ​

One reader refills; the rest wait or serve stale. The Go test proves one load for 200 callers. See Caching.

Control plane as a hidden dependency ​

Draw the dependency graph including DNS and discovery. The postmortem found data plane to control plane through DNS; the fix named is decoupling and tests that exercise losing the control plane.

Choosing ​

SituationChooseExtra techniqueReason (source)
Read-heavy product, hard-to-shard writesSingle primary plus replicasMove shardable writes outPostgreSQL post
Big MPI jobsOne pod per node, gang schedulingPreflight GPU tests7,500-node post
Mixed small and large clustersMany clusters, hub and spokeNo cross-cluster dependencies7,500-node post
Bulk non-interactive inferenceBatch API50% lower costBatch guide
Long stable promptsPrompt cachingStable prefix firstPrompt caching guide
Burst of API clientsRespect Retry-AfterRamp at most 50% per 15 minutesRate-limit guide
Shipping a new modelSystem card and red teamingPreparedness scorecardGPT-4o System Card
New fleet agentPhased rolloutTest at production sizeDecember 2024 post

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

A chat app begins as one web process and one PostgreSQL database. The OpenAI post describes this stage as the one it never really left for the main product data: a single primary. Use a connection pooler early and keep schema changes lightweight.

Modular monolith / multiple databases ​

Split by module with separate schemas: conversations, billing, usage. New write-heavy modules go to a different store (the post routes new workloads to sharded systems by default). Ownership is a rule: "no new tables" in the primary.

Microservices ​

Service-to-service calls need discovery. The December 2024 postmortem shows the price: discovery through Kubernetes DNS tied the data plane to the control plane. Keep a path that works with cached or static endpoints for critical services (inference, from the prevention list).

Distributed data (replicas, caches, sharding, multi-region) ​

Nearly 50 replicas across regions mean replication lag and WAL fan-out limits; cascading replication relays WAL through intermediate replicas. A Redis Cluster cache needs correct connection handling under cancellation, as the March 2023 bug showed.

Scaling path: 1x, 10x, 100x ​

LoadDoSource
1xOne primary, a pooler, rate limitsPostgreSQL post (pooling, limits)
10xAdd replicas, move shardable writes out, cache with leasesPostgreSQL post ("more than 10x" growth in a year)
100xCascading replication, workload isolation by tier, possibly sharded PostgreSQLPostgreSQL post ("continue to explore")

Lab ​

Expected, not run for the cluster steps; the Go tests are run.

# 1) Run the teaching code
cd docs/snippets/system-design/case-study-openai/go && go test ./...
# expected: ok for cachelock, gang, prefixcache, ratelimit, sse

# 2) etcd size and request rates on a cluster you own (expected, not run)
ETCDCTL_API=3 etcdctl endpoint status --write-out=table
# expected: DB SIZE column; compare with the 2 GB default limit
kubectl get --raw /metrics | grep apiserver_request_total | head
# expected: counters per verb and resource; look for LIST on events and endpoints

# 3) Check a limit's headers against any HTTP API (expected, not run)
curl -si https://api.example.com/v1/test | grep -i 'x-ratelimit\|retry-after'
# expected: remaining and reset values; Retry-After only on 429 or 503
  1. Edit prefixcache_test.go to share exactly 1,100 tokens; expected cached read: 1,024 (1,100 rounded down to a multiple of 128).
  2. Change the gang test to three jobs of 50 on 100 nodes; expected: two admitted, one rejected, and no stranded pods.
  3. Remove the lease in cachelock and count loads; expected: close to 200.
  4. In SQL, try the commented ALTER ... TYPE bigint on a large table; expected: a long table rewrite under a lock, which is why the post forbids it.

Common misconceptions ​

BeliefReality
OpenAI shards PostgreSQLThe 2026 post says one primary and nearly 50 replicas; shardable writes go to Cosmos DB
One cluster serves everythingHundreds of clusters (December 2024 post); training clusters isolated from each other
Kubernetes load balancing powers trainingThe 2021 post: very little HTTPS traffic, pods talk on pod IPs
More API servers fix etcd latency2018: the cause was etcd disk latency and apiserver polling
The data plane survives control plane lossDNS needed the API server in December 2024
A cache bug returns only stale dataMismatched data of the right type looked valid (March 2023)
Monitoring is harmlessA telemetry rollout caused the December 2024 outage
Public docs show the GPU stackThey show the client contract only
All numbers on blogs about OpenAI cost are factsCost of inference is not published in our sources; those are inference
System cards are marketingThey document red teaming and a scorecard used as a release gate

Cheat sheet ​

TopicRemember
Training podsOne per node, MPI, halt on any failure, checkpoint
etcdLatency-bound; local SSD; separate Events; 2 GB limit
API serversAvoid per-node polling; 70 GB heap at 7,500 nodes
EndpointSlices1000x less watch load
NetworkNative pod IPs, hub and spoke, isolated clusters
HealthPreflight taint, passive checks, cron GPU tests
SchedulingTaints for teams, balloons, Coscheduling
PostgreSQLOne primary, nearly 50 replicas, PgBouncer, lease, rate limits
SchemaLightweight only, 5 s timeout, concurrent indexes
Redis incidentCancelled request corrupts pooled connection; verify owner
December 2024Telemetry plus control plane plus DNS; phased rollouts
ServingSSE, RPM and TPM, Retry-After, Batch 50%, caching 1,024 tokens
SafetyModeration endpoint free, system card per model
LabelsCited, inference, ours

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Which component limited the 2018 cluster after 500 nodes, and what was the first fix? Good to know ​

Answer

Answer: etcd write latency on network SSD; moving etcd to local SSD cut latency from about 2 ms to 200 us.

2 — What stopped etcd writes at about 1,000 nodes and what did the autoscaler do? Good to know ​

Answer

Answer: The 2 GB default storage limit; nodes failed health checks and the autoscaler tried to terminate workers. A quota flag and a 50% sanity check fixed it.

3 — Why did EndpointSlices matter? Important ​

Answer

Answer: Every node watched the kubelet Endpoints, so payloads grew as N squared; EndpointSlices cut that load about 1000x.

4 — Why does gang scheduling exist for these jobs? Must-know ​

Answer

Answer: MPI groups need all members; default scheduling can start half of two jobs and deadlock both.

5 — How does OpenAI scale PostgreSQL without sharding it? Important ​

Answer

Answer: One primary with a hot standby, nearly 50 read replicas, PgBouncer, cache leases, rate limits, workload isolation, and shardable writes moved to Cosmos DB.

6 — What was the root cause of the March 2023 data exposure? Must-know ​

Answer

Answer: A redis-py asyncio bug: a cancelled request left a response on a pooled connection, which the next request read.

7 — Why did the December 2024 outage last 4 hours 22 minutes? Good to know ​

Answer

Answer: The control plane was overloaded, DNS depended on it, and the fix needed API access that was unavailable until clusters were scaled down and admin APIs blocked.

8 — What does the docs rule "Retry-After is a minimum" imply for a client? Important ​

Answer

Answer: Wait at least that long, add random jitter, bound attempts and total time.

9 — Why can prompt caching fail after a small prompt edit? Important ​

Answer

Answer: Reuse requires the entire rendered prefix to match; a change near the front invalidates everything after it.

10 — Name one claim on this page that is inference. Must-know ​

Answer

Answer: For example: the cost-per-token formula, the claim that InfiniBand carries the training traffic, or the tens of thousands of QPS per replica estimate.

Glossary ​

TermMeaning
OpenAIAI research and product company whose posts this chapter reads
ChatGPTOpenAI's chat product
7500 nodesThe cluster size in the January 2021 post
etcdReplicated key-value store holding Kubernetes state
Kubernetes control planeAPI servers, scheduler, controllers and etcd
Data planeNodes and pods that serve workloads
GPU schedulingPlacing pods on GPU nodes, including health and gangs
Gang schedulingAll members of a job start together or none do
CoschedulingKubernetes scheduler plugin for gangs
MPIMessage passing used across training pods
InfiniBandHigh-bandwidth, low-latency cluster network; not stated in OpenAI's posts we read
Training clusterNodes running model training jobs
Azure supercomputerMicrosoft infrastructure OpenAI runs on; figures not cited here
EndpointSlicesKubernetes API splitting endpoint lists to cut watch load
InferenceRunning a trained model to produce output
ServingThe system that answers inference requests
StreamingSending output as it is generated
SSEServer-sent events, one-way HTTP event stream
Rate limitCap on requests or tokens per time window
TokensUnits of text the model counts and bills
Batch APIAsynchronous bulk API, 24-hour window
Prompt cachingReuse of a shared prompt prefix
IdempotencySafe repeat of a request with the same effect
ModerationEndpoint that classifies harmful content
System cardPer-model safety and evaluation report
SafetyEvaluations and mitigations before and after release
PostmortemWritten analysis of an incident
IncidentAn unplanned degradation or outage
Telemetry service outageDecember 11, 2024 event
Redis-pyPython Redis client where the March 2023 bug lived
Data exposureData shown to someone not entitled to see it
PostgreSQL scalingSingle primary plus read replicas approach in the 2026 post
Read replicasCopies that serve reads
PgBouncerConnection pooler for PostgreSQL
WALWrite-ahead log streamed to replicas
ObservabilityMetrics, logs and traces used to understand a system
Cost of inferenceCompute cost per output token; not published in sources read
Inference (label)In this chapter, our own reasoning, marked inference

References ​

Every URL below returned HTTP 200 when fetched on 2026-11-26 and the page text was saved.

Not cited: Microsoft's announcement of the Azure supercomputer for OpenAI. Its pages did not load from the authoring machine, so no figure from them appears here.

Built by Morteza Negahi