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 for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| What can and cannot be known from public sources | Why it exists |
| Dated posts, 2018 to 2026 | Where it comes from |
| Step 1: what OpenAI says it runs | Scope |
| Step 2: the cited and estimated numbers | Estimate |
| Training clusters on Kubernetes, 2,500 then 7,500 nodes | Training cluster |
| etcd, API servers, EndpointSlices | etcd and API servers |
| Pod networking, hub and spoke | Networking |
| Health checks, preflight, GPU scheduling, gangs | GPU scheduling |
| Microsoft supercomputer, InfiniBand | Azure supercomputer |
| ChatGPT product data tier | PostgreSQL scaling |
| Redis cache, redis-py | Redis cache tier |
| API: streaming, rate limits, batch, caching | Serving contract |
| Moderation, system cards | Safety |
| Two postmortems | Incidents |
| What to copy | What you can copy |
| Code | Go, Laravel |
| Classic problems | Solving the classic problems |
| Decisions | Choosing |
| Monolith to distributed | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
Which layer, which source.
| Layer | What OpenAI published | Where | Status |
|---|---|---|---|
| Training clusters | Kubernetes at 2,500 nodes (2018) and 7,500 nodes (2021): etcd, API servers, networking, GPU health, gang scheduling | OpenAI blog | Cited |
| Product data tier | One PostgreSQL primary, nearly 50 read replicas, PgBouncer, cache locking, Azure Cosmos DB for shardable writes | OpenAI blog, January 2026 | Cited |
| Serving contract | SSE streaming, requests and tokens per minute, Batch API, prompt caching | Platform docs | Cited |
| Safety | A free moderation endpoint, system cards published per model | Platform docs, OpenAI blog | Cited |
| Reliability | Redis-py data exposure (March 2023), telemetry service outage (December 2024) | OpenAI blog, status page | Cited |
| Inference engine, GPU placement for serving, request routing | Not published in what we read | none | Inference only |
| Training fabric (InfiniBand) | Not stated in OpenAI's posts we fetched; Microsoft pages could not be fetched | none | Inference only |
The four steps applied.
| Step | Question | OpenAI answer (cited unless marked) |
|---|---|---|
| Scope | Who are the users and what are the workloads? | Research training jobs (MPI, GPUs); ChatGPT and API products with 800 million users |
| Estimate | How 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 design | What are the boxes? | Kubernetes per cluster, hub and spoke network, one PostgreSQL primary with replicas, Redis cache, Cosmos DB |
| Decisions | What 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).
| Number | Meaning | Source |
|---|---|---|
| 500 nodes | Where kubectl timeouts began (2018) | 2,500-node post |
| 2 GB | Default etcd storage limit that stopped writes | 2,500-node post |
| 5 API servers, 5 etcd nodes | Largest cluster layout (2021) | 7,500-node post |
| 70 GB | Heap per API server at 7,500 nodes | 7,500-node post |
| 1000x | Load reduction from EndpointSlices | 7,500-node post |
| Nearly 50 | Read replicas, several regions | PostgreSQL post |
| 5,000 | Connection limit per Azure PostgreSQL instance | PostgreSQL post |
| 50 ms to 5 ms | Average connection time with PgBouncer | PostgreSQL post |
| 1.2% | ChatGPT Plus subscribers whose payment data may have been exposed in a nine-hour window | March 2023 post |
| 3:16 PM to 7:38 PM PST | December 11, 2024 outage window | Status page |
| 50% and 24 hours | Batch API discount and completion window | Batch guide |
| 1,024 tokens | Minimum cacheable prompt length for GPT-5.6 and later | Prompt 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.
| Style | What you get | What you risk |
|---|---|---|
| Cited-only reading (this page) | Facts you can check | Gaps where the company is silent |
| Inference to fill the gaps | A complete picture | Confident fiction; always label it |
| Copying the architecture | Fast start | Copying 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
- "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.
- "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.
- "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 cachingWhat changed over time, as a table (cited from the posts above):
| Concern | 2018 | 2021 | 2024 to 2026 |
|---|---|---|---|
| Cluster size | Over 2,500 nodes | 7,500 nodes | Hundreds of clusters (December 2024 post) |
| Pod network | Flannel, about 2 Gbit/s in pods vs 10 to 15 Gbit/s between machines | Native pod networking on Azure VMSS, host-level throughput | Not covered in what we read |
| etcd | Local SSD, separate Events etcd | 5 etcd nodes, "no notable trouble" | API server and DNS dependency named as the risk |
| Scheduling | MostRequestedPriority to pack nodes for the autoscaler | Coscheduling plugin for gangs | Not covered |
| Data tier | Not covered | Not covered | PostgreSQL single primary, nearly 50 replicas |
| Failure style | etcd limit cascades to autoscaler | Prometheus OOM and WAL replay | Telemetry 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.
| Quantity | Value | Label |
|---|---|---|
| Users behind the PostgreSQL deployment | 800 million | Cited (post title) |
| PostgreSQL QPS | millions | Cited |
| Read replicas | nearly 50 | Cited |
| Average QPS per replica if load were even | on 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 serve | one per replica, nearly 50 | Cited mechanism, count inferred from "primary must stream WAL to every replica" |
| Tokens per second at a 1,000,000 TPM limit | about 16,700 | Ours (1,000,000 / 60) |
| Cost of one cached read vs normal input | 0.1x at the rate quoted in the docs | Cited |
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 checkpointReal 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.
| Property | Cited value | Why it matters |
|---|---|---|
| Pod placement | Often a single pod on an entire node | No NUMA or PCIe contention for the scheduler to solve |
| Network | Full bisection bandwidth | No rack or topology awareness needed |
| Service discovery | One-time lookup at job startup | Kubernetes Services barely used |
| Storage | Mostly blob storage, few PersistentVolumes | Avoids 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:
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 clusterReal 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 fact | Where | Value or effect (cited) |
|---|---|---|
--quota-backend-bytes | etcd | Raises the 2 GB default storage limit |
--etcd-servers-overrides | kube-apiserver | Sends /events to a separate etcd |
--apiserver-count | kube-apiserver (2018) | Number of API servers, to keep Prometheus unconfused |
| 5 API servers, 5 etcd | 2021 layout | Run outside the cluster on dedicated nodes |
| Heap per API server | 7,500 nodes | Up to 70 GB |
| 429 and 5xx rates | Alerts | A high-level signal of API server trouble |
| Autoscaler sanity check | Autoscaler | Refuses 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| Choice | Reason given | Consequence |
|---|---|---|
| Alias-based IPs, no route-based pod networking | About 200,000 IPs in use at once; route limits | Simple network, no MTU surprises |
| iptables mangle rules marking internet-in and internet-out | Per-namespace bandwidth visibility | Counters exported by iptables-exporter |
| Hub and spoke | Isolation, no cross-cluster dependencies | A 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| Mechanism | Detail from the post | Purpose |
|---|---|---|
| DCGM and dcgm-exporter | DCGM_FI_DEV_XID_ERRORS metric into Prometheus | Detect "Uncorrectable ECC error" and other Xid errors |
| Preflight taint | Added to every node at boot | No jobs on an untested GPU |
| team-resource-manager | ConfigMap of (node selector, team label, amount) plus admission webhook | Team capacity with borrowing through an "any" toleration |
| CPU and GPU balloons | Low-priority pods in a Deployment, max-size replicas | Keep autoscaler from removing idle nodes; evicted instantly for real work |
| Coscheduling plugin | Scheduler plugin architecture, Kubernetes 1.18 | All pods of a gang or none |
| Priority policy (2018) | MostRequestedPriority weight 1, InterPodAffinityPriority weight 2 | Pack 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.
| Item | Status |
|---|---|
| NVLink and GPUDirect inside nodes | Cited (7,500-node post) |
| Full bisection bandwidth | Cited |
| InfiniBand between nodes | Not cited; inference only |
| Total GPU count of any cluster | Not 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 post | Solution (cited) | Our generic chapter |
|---|---|---|
| One writer cannot scale writes | Move shardable write-heavy workloads to Cosmos DB; fix redundant writes; lazy writes; rate-limited backfills | Sharding at System Level |
| Expensive queries (a 12-table join) | Move join logic to the application; review ORM SQL; fix long idle queries | ORM Pitfalls |
| Single point of failure | Hot standby in HA mode; critical reads on replicas | Replication Topologies |
| Noisy neighbour | Low and high priority tiers on separate instances | Bulkheads |
| Connection limit (5,000 per instance) | PgBouncer in transaction or statement mode | Connection Pooling |
| Cache miss storms | Cache locking and leasing | Caching |
| WAL to every replica | Cascading replication in testing, possibly over a hundred replicas | Replication, Read Replicas & Failover |
| Retry storms, expensive query spikes | Rate limits at app, pooler, proxy and query layers; block a query digest | Load Shedding |
| Schema changes rewrite tables | Lightweight changes only; 5-second timeout; concurrent index builds; no new tables | Zero-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:
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 validAt 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 tested | Root 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 users | Incident response |
| Improved logging and the robustness and scale of the Redis cluster | Detection 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).
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:
| Feature | What 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 limits | RPM, 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 API | JSONL file, 50% lower cost, 24-hour completion window, queued-token limit separate from per-minute limits, 200 MB upload limit | Move non-interactive work off the hot path |
| Prompt caching | Reuse of a shared prompt prefix; minimum 1,024 tokens for GPT-5.6 and later; reads rounded down to a multiple of 128 | Put 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-After | Minimum seconds to wait on a temporary 429 or 503 |
x-ratelimit-limit-requests, x-ratelimit-limit-tokens | Budget |
x-ratelimit-remaining-requests, x-ratelimit-remaining-tokens | What is left |
x-ratelimit-reset-requests, x-ratelimit-reset-tokens | When it refills |
x-ratelimit-limit-project-tokens and project variants | Project-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).
| Mechanism | Cited facts | As a design constraint |
|---|---|---|
| Moderation endpoint | Model omni-moderation-latest, text and image input, free | Add a pre-check or post-check hop with its own timeout and fallback (inference) |
| System card | Published per model; includes red teaming, evaluations, scorecard | Release gate and documentation artefact |
| Preparedness scorecard | Categories scored; GPT-4o voice scored low in three of four, persuasion borderline medium | A 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 cause | Telemetry configuration made every node run resource-intensive Kubernetes API operations whose cost scaled with cluster size |
| Not caught | Staging 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 recovery | Fixing needed access to the API servers that were overwhelmed |
| Mitigations used | Scale 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.
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.
| Signal | Source (cited) | Question answered |
|---|---|---|
| API server 429 and 5xx | Grafana dashboards | Is the control plane overloaded? |
DCGM_FI_DEV_XID_ERRORS | dcgm-exporter | Is a GPU failing? |
| Internet in and out per namespace | iptables mangle counters | Who is using bandwidth? |
| Nodes and pending pods | Dashboards | Is 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 subsystem | The generic idea | Chapter | Copy when |
|---|---|---|---|
| Separate Events etcd | Isolate a noisy write stream from the core store | Containers & Kubernetes | Your cluster has more than a few hundred nodes |
| Gang scheduling | All-or-nothing admission | Containers & Kubernetes | Jobs need every member to start |
| Single primary + replicas | Scale reads first, move shardable writes out | Replication Topologies | Read-heavy, hard to shard |
| PgBouncer per replica | Pooling near the database | Connection Pooling | Connection limits hurt |
| Cache lease | One refill per key | Caching | Cache miss storms |
| Token and request budgets | Limit on cost, not on calls | Rate Limiting | Calls vary in size |
| Batch API | Async bulk lane at lower price | Serverless & Event-Driven Compute | Work is not interactive |
| Phased rollouts | Limit blast radius | Chaos Engineering | Any fleet-wide change |
| System card | Documented release gate | Secure SDLC & Incident Response | You 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
| Knob | Component | Value or note |
|---|---|---|
--quota-backend-bytes | etcd | Raise from the 2 GB default |
--etcd-servers-overrides | kube-apiserver | /events#https://... to a separate etcd |
--serialize-image-pulls | kubelet | Default true; set false (needs overlay2) |
--image-pull-progress-deadline | kubelet | Set to 30 minutes in 2018 |
max-concurrent-downloads | Docker daemon | Set to 10 |
GOMAXPROCS | Prometheus | 24 improved WAL replay |
| Pod Disruption Budget | Pod | Decides if an eviction is allowed |
Taint openai.com/team=teamname:NoSchedule | Nodes | Team quota |
| Connection limit | Azure PostgreSQL | 5,000 per instance |
| Schema change timeout | PostgreSQL deployment | 5 seconds |
prompt_cache_key | Responses API | Request field named in the caching guide |
completion_window | Batch API | Only 24h |
Errors and messages
| Message or code | Context | Meaning |
|---|---|---|
rpc error: code = 2 desc = net/http: request canceled | 2018 image pulls | Pull taking too long without progress |
| HTTP 429 | API | Rate limit or slow_down ramp limit |
HTTP 503 server_is_overloaded | API | Model overload; use Retry-After |
query processing would load too many samples | Prometheus | Query too wide for storage |
| Uncorrectable ECC error (Xid) | GPU | Hardware fault; reset or replace |
Limits and defaults
| Item | Value | Source |
|---|---|---|
| Batch input file | well below 200 MB | Batch guide |
| Moderation image | up to 20 MB | Moderation guide |
| Cache breakpoints per request | up to four writes | Prompt caching guide |
| Ramp rule | at most 50% every 15 minutes above 1M TPM | Rate-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:
// 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))
}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.
// 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()
}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):
// 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()
}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:
// 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
}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")
}
}// 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
}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:
-- 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):
SET lock_timeout = '5s';
ALTER TABLE usage_ledger ADD COLUMN batch_id text; -- no table rewriteThe Go angle
net/httpwith anhttp.Flusheris all SSE needs; always watchr.Context().Done()so a closed client stops generation.- A
sync.WaitGroupper in-flight key is a small single-flight; the standard extended library hasgolang.org/x/sync/singleflightfor the same idea. - Use
time.Durationarithmetic in one place forRetry-Afterplus 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
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
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
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()andStreamedEventare documented in the Laravel 13 responses docs; the JavaScript side can use the@laravel/stream-reactor@laravel/stream-vuepackages 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::flexibleimplements stale-while-revalidate and is another way to avoid refill stampedes.Http::retry(3, 100)retries with a fixed delay; for 429 withRetry-Afterpass 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
| Problem | Solution | How | Cost or limit |
|---|---|---|---|
| kubectl timeouts at scale | Fix etcd first | Local SSD, separate Events etcd | More etcd clusters to run |
| Fleet-wide scale-down after storage limit | Autoscaler sanity check | Refuse more than 50% termination | Slower legitimate scale-down |
| Watch fan-out | EndpointSlices | Avoid N squared watch payloads | Needs Kubernetes 1.17 or later |
| Half-scheduled jobs | Gang scheduling | Coscheduling plugin | Plugin to maintain |
| Single writer saturates | Offload reads, shard writes elsewhere | Replicas, Cosmos DB | Two data systems |
| Miss storm | Lock and lease | One reader refills | Waiters add latency |
| Retry storm | Layered rate limits, jittered retries | App, pooler, proxy, query | Some requests rejected |
| Wrong-user cache data | Verify owner on read | Redundant check | Small CPU cost |
| Control plane overload | Phased rollout and break-glass access | One cluster at a time | Slower 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
| Situation | Choose | Extra technique | Reason (source) |
|---|---|---|---|
| Read-heavy product, hard-to-shard writes | Single primary plus replicas | Move shardable writes out | PostgreSQL post |
| Big MPI jobs | One pod per node, gang scheduling | Preflight GPU tests | 7,500-node post |
| Mixed small and large clusters | Many clusters, hub and spoke | No cross-cluster dependencies | 7,500-node post |
| Bulk non-interactive inference | Batch API | 50% lower cost | Batch guide |
| Long stable prompts | Prompt caching | Stable prefix first | Prompt caching guide |
| Burst of API clients | Respect Retry-After | Ramp at most 50% per 15 minutes | Rate-limit guide |
| Shipping a new model | System card and red teaming | Preparedness scorecard | GPT-4o System Card |
| New fleet agent | Phased rollout | Test at production size | December 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
| Load | Do | Source |
|---|---|---|
| 1x | One primary, a pooler, rate limits | PostgreSQL post (pooling, limits) |
| 10x | Add replicas, move shardable writes out, cache with leases | PostgreSQL post ("more than 10x" growth in a year) |
| 100x | Cascading replication, workload isolation by tier, possibly sharded PostgreSQL | PostgreSQL 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- Edit
prefixcache_test.goto share exactly 1,100 tokens; expected cached read: 1,024 (1,100 rounded down to a multiple of 128). - Change the gang test to three jobs of 50 on 100 nodes; expected: two admitted, one rejected, and no stranded pods.
- Remove the lease in
cachelockand count loads; expected: close to 200. - In SQL, try the commented
ALTER ... TYPE biginton a large table; expected: a long table rewrite under a lock, which is why the post forbids it.
Common misconceptions
| Belief | Reality |
|---|---|
| OpenAI shards PostgreSQL | The 2026 post says one primary and nearly 50 replicas; shardable writes go to Cosmos DB |
| One cluster serves everything | Hundreds of clusters (December 2024 post); training clusters isolated from each other |
| Kubernetes load balancing powers training | The 2021 post: very little HTTPS traffic, pods talk on pod IPs |
| More API servers fix etcd latency | 2018: the cause was etcd disk latency and apiserver polling |
| The data plane survives control plane loss | DNS needed the API server in December 2024 |
| A cache bug returns only stale data | Mismatched data of the right type looked valid (March 2023) |
| Monitoring is harmless | A telemetry rollout caused the December 2024 outage |
| Public docs show the GPU stack | They show the client contract only |
| All numbers on blogs about OpenAI cost are facts | Cost of inference is not published in our sources; those are inference |
| System cards are marketing | They document red teaming and a scorecard used as a release gate |
Cheat sheet
| Topic | Remember |
|---|---|
| Training pods | One per node, MPI, halt on any failure, checkpoint |
| etcd | Latency-bound; local SSD; separate Events; 2 GB limit |
| API servers | Avoid per-node polling; 70 GB heap at 7,500 nodes |
| EndpointSlices | 1000x less watch load |
| Network | Native pod IPs, hub and spoke, isolated clusters |
| Health | Preflight taint, passive checks, cron GPU tests |
| Scheduling | Taints for teams, balloons, Coscheduling |
| PostgreSQL | One primary, nearly 50 replicas, PgBouncer, lease, rate limits |
| Schema | Lightweight only, 5 s timeout, concurrent indexes |
| Redis incident | Cancelled request corrupts pooled connection; verify owner |
| December 2024 | Telemetry plus control plane plus DNS; phased rollouts |
| Serving | SSE, RPM and TPM, Retry-After, Batch 50%, caching 1,024 tokens |
| Safety | Moderation endpoint free, system card per model |
| Labels | Cited, inference, ours |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| OpenAI | AI research and product company whose posts this chapter reads |
| ChatGPT | OpenAI's chat product |
| 7500 nodes | The cluster size in the January 2021 post |
| etcd | Replicated key-value store holding Kubernetes state |
| Kubernetes control plane | API servers, scheduler, controllers and etcd |
| Data plane | Nodes and pods that serve workloads |
| GPU scheduling | Placing pods on GPU nodes, including health and gangs |
| Gang scheduling | All members of a job start together or none do |
| Coscheduling | Kubernetes scheduler plugin for gangs |
| MPI | Message passing used across training pods |
| InfiniBand | High-bandwidth, low-latency cluster network; not stated in OpenAI's posts we read |
| Training cluster | Nodes running model training jobs |
| Azure supercomputer | Microsoft infrastructure OpenAI runs on; figures not cited here |
| EndpointSlices | Kubernetes API splitting endpoint lists to cut watch load |
| Inference | Running a trained model to produce output |
| Serving | The system that answers inference requests |
| Streaming | Sending output as it is generated |
| SSE | Server-sent events, one-way HTTP event stream |
| Rate limit | Cap on requests or tokens per time window |
| Tokens | Units of text the model counts and bills |
| Batch API | Asynchronous bulk API, 24-hour window |
| Prompt caching | Reuse of a shared prompt prefix |
| Idempotency | Safe repeat of a request with the same effect |
| Moderation | Endpoint that classifies harmful content |
| System card | Per-model safety and evaluation report |
| Safety | Evaluations and mitigations before and after release |
| Postmortem | Written analysis of an incident |
| Incident | An unplanned degradation or outage |
| Telemetry service outage | December 11, 2024 event |
| Redis-py | Python Redis client where the March 2023 bug lived |
| Data exposure | Data shown to someone not entitled to see it |
| PostgreSQL scaling | Single primary plus read replicas approach in the 2026 post |
| Read replicas | Copies that serve reads |
| PgBouncer | Connection pooler for PostgreSQL |
| WAL | Write-ahead log streamed to replicas |
| Observability | Metrics, logs and traces used to understand a system |
| Cost of inference | Compute 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.
- OpenAI, Scaling Kubernetes to 7,500 nodes (2021-01-25)
- OpenAI, Scaling Kubernetes to 2,500 nodes (2018-01-18)
- OpenAI, Scaling PostgreSQL to power 800 million ChatGPT users (2026-01-22)
- OpenAI, March 20 ChatGPT outage: Here's what happened (2023-03-24)
- OpenAI Status, API, ChatGPT and Sora Facing Issues (2024-12-11)
- OpenAI, GPT-4o System Card (2024-08-08)
- OpenAI Platform, Streaming API responses
- OpenAI Platform, Rate limits
- OpenAI Platform, Batch API
- OpenAI Platform, Prompt caching
- OpenAI Platform, Moderation
- Laravel 13, Rate limiting, Responses, Cache, HTTP client
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.