Skip to content

Stripe Engineering: API Design and Financial Correctness

Advanced 147 min read Part 18 of 18

How Stripe keeps a money-moving API safe to retry and correct to the cent: idempotency, versioning, rate limits, migrations, ledgers and fraud ML.

Summary#

Stripe runs an API that moves money for millions of businesses. Two promises shape almost every engineering post it has published. First, the API is infrastructure: an integration written years ago must keep working without changes, and a retried request must never charge a customer twice. Second, money must be correct to the cent: every movement of funds must be recorded, explained and matched against what the banks and card networks say happened. This page reads 29 Stripe engineering posts, written between 2017 and 2026, through the same four lenses used across this part of the handbook: the assumptions the engineers made, the architecture they built, the constraints that are easy to miss, and what Stripe gave up to get there.

The posts fall into seven families: the API contract (idempotency, the PaymentIntents state machine, versioning, the API change pipeline), protecting the API (rate limiters, load shedders, client-side throttling, webhooks), changing data safely (online migrations, a document database migration platform, database auto-remediation, a 2019 incident), seeing the system (canonical log lines, the Veneur metrics pipeline, DNS, a data plane proxy), money correctness (the ledger, reconciliation, credits, global money movement, a charged-twice bug, thin events), machine learning (Radar, Railyard, Shepherd and Chronon, real-time billing analytics) and developer productivity (selective test execution, tax jurisdiction resolution). All Stripe facts below come from the fetched posts. Math, analogies and general engineering context are the handbook's own explanation.

Why It Exists#

Most companies can afford a bad deploy that returns a few errors for ten minutes. A payments company cannot afford the same bug, because the cost is not a retry. It is a customer charged twice, a merchant paid the wrong amount, or a bank file that does not match the books. Stripe's posts are valuable because they show what changes when correctness is the product:

  • An HTTP timeout is not just an error. It is an ambiguous outcome: the card may or may not have been charged.
  • An API field rename is not a refactor. It is a breaking change to thousands of businesses whose code expects the old name.
  • A database migration is not a weekend job. It must happen while the API keeps serving at very high availability.
  • A metric is not a nice-to-have. When money is wrong, engineers need to find the exact request, the exact ledger entry and the exact bank file line that disagree.

The textbook version of a payment system (see Design a Payment System) lists the right components: an idempotent API, a ledger, reconciliation, retries. Stripe's posts show how those components behave after ten years of real traffic, real banks and real API users who never upgrade.

For each post the page asks:

  1. Assumptions. What traffic, latency, consistency and maintenance conditions did the authors assume?
  2. Production architecture. What did Stripe actually build?
  3. Overlooked constraints and trade-offs. What is easy to miss when copying the idea?
  4. Sacrifice. What did Stripe give up to get the benefit?

How It Works#

The diagram groups the posts by the question each one answers. A request enters through a stable contract, is admitted or shed, changes data that may be in the middle of a migration, is observed, moves money that must balance, and feeds models that decide whether the next payment is fraud.

Lesson 1: Designing robust and predictable APIs with idempotency#

Assumptions. The 2017 post starts from a blunt premise: networks between servers are more reliable than home Wi-Fi, but at Stripe's volume they still fail all the time at some background rate. A "distributed system" here can be as small as one merchant server calling the Stripe API. Any call can fail in three places:

  1. The connection fails before the server sees the request.
  2. The call fails midway while the server is doing the work.
  3. The work succeeds, but the response is lost before the client reads it.

Only the first case is unambiguous. In the second and third, the client cannot know whether the charge happened. That uncertainty is the whole problem.

Production architecture. Stripe's answer has two layers.

  • Naturally idempotent verbs. A call is idempotent if making it many times has the same effect as making it once. HTTP defines PUT (create or replace a resource with this exact content) and DELETE as idempotent. The post's example is a hypothetical DNS API: a PUT that creates a CNAME record carries the full desired state, so a duplicate can be ignored and answered with success. (PATCH is the verb for partial changes and is not idempotent in general.)
  • Idempotency keys for everything else. Some operations must happen exactly once, and charging a card is the obvious one. For these, the client generates a unique ID for the operation and sends it in an Idempotency-Key header. Stripe accepts the header on all mutating (POST) endpoints. The server stores the key with the state of the request. A retry with the same key then lands in one of three places:
    • If the first attempt never arrived, the server sees the key for the first time and processes it normally.
    • If the first attempt failed midway and the database rolled it back (an ACID database guarantees all-or-nothing transactions), the retry runs the work again from the start. If not, the server recovers the saved state and continues.
    • If the first attempt succeeded but the response was lost, the server returns the cached result of the first attempt without doing the work again.

The third pillar is client behaviour. Stripe's Ruby library retries failed requests automatically, reusing the same idempotency key, with exponential backoff (wait about 2^n units after the n-th failure) and random jitter (a random part of the wait). Without jitter, thousands of clients that failed at the same moment would retry at the same moment, a thundering herd. The post closes with three principles: handle failures consistently (always retry), safely (with idempotency keys) and responsibly (with backoff and jitter).

Overlooked constraints.

  • The key belongs to the operation, not to the HTTP attempt. If a client generates a fresh key on each retry, the server sees two different operations and charges twice. The key must be created once (for example when the order is created) and stored, so that a restarted process can reuse it.
  • Mid-request failures are the hard case. The post says the behaviour "depends heavily on implementation". A charge touches an external card network that is not part of Stripe's database transaction, so it cannot simply be rolled back. A safe server records progress in steps and, on retry, resumes from the last completed step instead of starting over. The idempotency page shows that design in detail.
  • Backoff without jitter only moves the spike. The thundering herd problem is exactly what happens when every client uses the same deterministic schedule.
  • Retries must stop. A client that retries forever turns an outage into a self-inflicted load test. Backoff caps and a maximum number of attempts are part of "responsible".

What Stripe sacrificed. Every mutating request now needs a lookup and a write to an idempotency store before the real work starts, which adds latency and storage. Clients must take on work too: generate keys, persist them, and accept that a retry can return a stale cached result rather than a fresh computation. Stripe accepted that cost because the alternative is double charges, which no amount of speed makes up for.

Deep Dive: how often ambiguity happens, and the backoff arithmeticShow

Ambiguity is a volume problem. Suppose 0.01% of calls end with a lost response or a mid-request failure. That sounds tiny. At 100 million mutating calls a day it is 10,000 ambiguous outcomes a day, about one every nine seconds. Without idempotency keys each one is a coin flip between "customer was not charged" and "customer will be charged twice if we retry". At that rate a manual process cannot keep up. The only scalable answer is one that makes retrying always safe.

Exponential backoff. If the base wait is b and the n-th retry waits b · 2^n, the total time spent waiting before the k-th retry is b · (2^k − 1). With b = 0.5 s and 4 retries the client has waited 0.5 + 1 + 2 + 4 = 7.5 s. A cap (say 8 s) stops the series growing without bound. With full jitter each wait is drawn uniformly from [0, b · 2^n], so the expected wait halves and arrivals spread evenly over the window.

Why jitter matters, in numbers. Imagine 50,000 merchant servers lose connectivity during the same 2-second network blip. With pure exponential backoff and b = 0.5 s, all 50,000 retry together at t = 0.5 s, then again at 1.5 s, then at 3.5 s. Each wave is a 50,000-request spike in a few milliseconds. With full jitter on the first retry, the 50,000 retries spread over 0.5 s, which is about 100 requests per millisecond: a load a healthy API absorbs without noticing.

A server-side recipe (handbook's illustration, not Stripe code). Store a row per (account, key) with the request fingerprint, a status (started, finished) and the response. On arrival: insert the row if absent. If it exists and is finished, return the stored response. If it exists and is started, either wait, return a "request in progress" error, or resume from the recorded step. If the fingerprint differs, reject the call: the client reused a key for a different operation.

Lesson 2: Stripe's payments APIs, the first 10 years#

Assumptions. In 2011 Stripe's API was built for US card payments. Its famous pitch was a few lines of curl: send a card Token (created in the browser by Stripe.js, so merchants avoid most card-data compliance work under PCI, the card industry's security standard) and get back a successful Charge. That design assumed that payments are finalized immediately (the merchant knows at once that funds are guaranteed) and that no customer action is needed after the card number is typed. Both assumptions held for US cards and broke for almost everything else.

Production architecture. The 2020 post by Michelle Bu tells the story in five steps.

  1. Cards (2011 to 2015). Token on the client, Charge on the server, one synchronous request.
  2. ACH and Bitcoin (2015). ACH debit (US bank-to-bank transfers) needs only static data like a card does, but finalizes days later. Stripe extended Token to bank accounts and added a pending state to Charge; merchants learned of success through a webhook days later. Bitcoin needs the customer to send funds, and a transaction needs about six blocks (roughly an hour) to be final. Stripe added a separate BitcoinReceiver object, a temporary holder of funds with a single boolean state (filled). Merchants now juggled two state machines: the receiver on the client and the Charge on the server.
  3. Sources (2015 to 2017). More payment methods arrived (iDEAL, Alipay, giropay, Bancontact, WeChat Pay, SEPA and Bacs direct debit, cards with 3D Secure, OXXO cash vouchers and more), and most needed customer action. Stripe merged Token and receiver into one client-side object, the Source, which was either chargeable at once or pending. The server still created a Charge from it. The rough edge was conversion: with iDEAL, if the customer paid at their bank and then closed the tab, the merchant server never created the Charge, and Stripe refunded the money hours later. The fix was "listen for the source.chargeable webhook and create the Charge there", which put a webhook handler in the critical path of collecting money. If the merchant's server was down, money went back to the customer.
  4. Design from first principles (late 2017 to early 2018). A team of five (four engineers and a PM) spent three months in a conference room designing for every payment method they knew or could imagine, including a made-up "cash by carrier pigeon". Their working rules: close laptops, collect new questions for the next session instead of chasing them now, use colours and shapes instead of premature names, write hypothetical integration guides to test each design, question every old assumption, invite domain experts, and decide quickly even if a decision is reversed later.
  5. PaymentIntents and PaymentMethods (2018 to 2020). A PaymentMethod is the "how": static credentials such as card details, or just the method's name for redirect methods like Alipay. A PaymentIntent is the "what": the amount and currency, and the single stateful object that tracks every attempt to pay. Rollout took almost two years.

The PaymentIntent state machine is the heart of the design. There is deliberately no failed state. A failed attempt returns the intent to requires_payment_method, so the customer can try another method on the same object.

The integration is now the same for every method: the server creates the intent, the client confirms it with the intent's secret and the customer's payment method, the client performs whatever requires_action asks (a redirect, a 3D Secure challenge, displaying OXXO voucher details), and the merchant fulfils the order on the payment_intent.succeeded webhook or when the intent reaches succeeded. Crucially, that one required webhook is not in the critical path of collecting money: if the merchant is down, the money is still collected, and fulfilment simply waits.

The post's key insight is a two-by-two table. Payment methods differ on two axes: is the payment finalized immediately or later, and does it need customer action to start? Cards are the only method in the "immediate, no action" corner. The post puts it as: global payment methods are not the odd ones, cards are. Stripe had built every abstraction around the single simplest case.

Overlooked constraints.

  • Migration shapes the design. Stripe could not force users to move. Many integrations also read Charge objects for analytics or support, sometimes owned by another team. So each PaymentIntent attempt still creates a Charge, letting old reporting code keep working. This is also why Charge was not repurposed: too much code assumed what a Charge meant.
  • Bloat control. Between 2011 and 2018 Charge grew from 11 properties to 36, and its create call from 5 parameters to 14. New method-specific data now goes into a typed, polymorphic payment_method_details hash rather than new top-level fields.
  • Simplicity got worse for the most valuable user. A US card-only startup now had to flip the client and server calls and handle webhooks. Stripe first showed different guides by user location, which confused developers whose business was in a different country from them. The final fix was a packaging: the error_on_requires_action=true parameter, documented as "card payments without bank authentication". It makes a PaymentIntent behave like the old synchronous Charge, tells the user clearly what they give up, and lets Stripe measure how many users choose it.
  • An API product is more than an API. Docs, support articles, community content, the Stripe CLI (which made webhooks easier to test), samples and the Dashboard view of the state machine all had to change.

What Stripe sacrificed. The magic "seven lines of code" experience for cards. Stripe accepted a higher up-front effort for every user in exchange for a low, predictable cost per additional payment method. It also accepted a permanent compatibility layer: a Charge for every PaymentIntent attempt, kept alive for integrations that may never move.

Deep Dive: the power-to-effort curve, as a simple cost modelShow

The post describes two curves: Charges are cheap to start and expensive per extra payment method; PaymentIntents are more expensive to start and cheap per extra method. A linear model makes the trade-off concrete. Let integration effort for n payment methods be E(n) = a + b·n.

IntegrationFixed cost aPer-method cost bEffort for 1 methodEffort for 6 methods
Charges and Sources1 day3 days4 days19 days
PaymentIntents3 days0.5 days3.5 days6 days

(The numbers are illustrative, not Stripe's.) The curves cross where 1 + 3n = 3 + 0.5n, at n = 0.8. In this toy model PaymentIntents wins even for one method. The real gap for card-only users is in the kind of work: webhooks and reversed call order are unfamiliar to classic web apps, so their perceived a is much higher. That is why the error_on_requires_action packaging matters: it lowers a for the card-only case without changing the objects underneath, so moving to the global integration later means removing a parameter, not rewriting.

Counting moving parts. The post counts the Charges-and-Sources "best practice" for cards, iDEAL and ACH: two webhook handlers (one time-critical), three moments when a Charge could succeed, two failure paths and two stateful objects. With PaymentIntents: one webhook handler (not time-critical), one state machine, one success state. Every removed branch is a class of bug that integrators can no longer write. This is a general rule of API design: two overloaded abstractions are harder to use than four clear ones.

Lesson 3: APIs as infrastructure, future-proofing Stripe with versioning#

Assumptions. The 2017 post compares an API to a power grid: once connected, it should run unchanged for as long as possible. Stripe had kept every API version compatible since 2011. It treats a change as backwards-incompatible if existing code could break: removing a field, renaming it or changing its type. The post's example is replacing a bank account's verified boolean with a status field in 2014. Adding a new endpoint or a new field is safe.

Production architecture. The usual industry approach is major versions in the URL (/v1/widgets, /v2/widgets) or in a header such as Accept. Stripe rejects that as its main tool: big version jumps are nearly as painful as reintegrating, some users never move, and the provider must either cut them off or maintain old versions forever. Stripe instead uses rolling, date-named versions such as 2017-05-24. Each one contains a small set of breaking changes, so upgrading one step is cheap.

  • On a user's first request, their account is pinned to the newest version. Every later call implicitly uses that version, so nobody receives a breaking change by accident.
  • A request can override the version with a Stripe-Version header, and users can move their pinned version in the Dashboard.
  • The /v1 prefix still exists but had not changed in six years and almost a hundred breaking changes. (A later post, covered in Lesson 4, describes a new v2 namespace introduced in 2024.)

Under the hood, every response shape is an API resource class written for the current version only. Each breaking change lives in a version change module that carries a description, the resource types it touches and a transformation that turns the new shape into the old one. A master list maps each date to its change modules. To render a response, the API builds the current shape, picks a target version (the Stripe-Version header, else the OAuth application's version when acting for a platform, else the account's pinned version), then walks backwards in time, applying each change module until it reaches the target.

Some changes are not just a different response shape. They change behaviour. These are marked has_side_effects, their transformation becomes a no-op, and code elsewhere checks VersionChanges.active?(...). The post admits these leak complexity into the core code and are avoided where possible. Because change modules are declarative, Stripe generates its public changelog from them and annotates its API reference for each logged-in user, warning about fields that changed since their pinned version.

Overlooked constraints.

  • Version changes must be written against the shape at their own time. Each module assumes that the data it receives looks the way it did when the module was written, regardless of later changes. Chaining works only because they are applied strictly in order.
  • The best version change is the one you never need. Stripe runs a lightweight API review: each outgoing change gets a short design document sent to a mailing list, so mistakes are caught before they become permanent.
  • Compatibility forever is not free. The post says Stripe expects to retire old versions eventually, because each side-effect check left in the code makes it slower and more fragile.
  • Webhooks need versions too. Event payloads are rendered through the same machinery, which the example change module (collapsing an event's request field into a sub-object) shows.

What Stripe sacrificed. Engineering simplicity in the request path: every response pays for a chain of transformations, and every engineer must think about versions when changing a resource. Stripe chose to make old versions a fixed cost (encapsulated, tested modules) rather than a growing tax spread across the code. The post's three principles are that upgrades must be lightweight, versioning must be first-class (driving docs and changelog), and old versions must be fixed-cost.

Deep Dive: versioning schemes compared, and the cost of walking backShow

Where the version lives. There are three common places, and Stripe uses two of them at once:

SchemeExampleStrengthWeakness
URL path/v1/chargesVisible, cache-friendly, easy routingCoarse; a new major version forks every URL
HeaderStripe-Version: 2017-05-24 or Accept: application/vnd.x.v2+jsonFine-grained, URLs stay stableInvisible in logs and browsers unless recorded
Account pinningVersion stored on the account at first callZero configuration, no accidental upgradesBehaviour depends on hidden account state

Cost of a response. If an account is pinned k versions behind and each version has on average m change modules, a response passes through about k · m transformations, but only those that apply to its resource type. Each is a small hash rewrite, microseconds of CPU. With about a hundred changes over six years, an old integration might pass through a few dozen, which is negligible next to a database read. The real cost is not CPU but combinations: every change is tested in isolation, yet a response from 2014 runs through all of them in sequence. Keeping each module pure (data in, data out) is what keeps that chain testable.

Why date versions beat semantic versions here. A semantic version (2.3.1) tells you how big the change is. A date tells you when it happened, and since every account is pinned to a date, the date also tells Stripe exactly which modules to apply. Small, frequent breaking changes make each upgrade a short checklist instead of a migration project.

Lesson 4: How API changes flow into Stripe's developer products#

Assumptions. By 2026 an API change at Stripe is not finished when the pull request merges. The same change must reach SDKs in seven languages across three release channels, the CLI, the Stripe Shell and API Explorer, the API reference, the public changelog and internal tools used by engineers and AI agents. Doing that by hand guarantees drift.

Production architecture. The backbone is OpenAPI, the industry-standard format for describing HTTP APIs. Stripe used it internally from 2016, published a public OpenAPI description in 2017, and in 2019 generated an SDK from it for the first time (stripe-java 8.0). But adoption was uneven: the API reference, for example, parsed Stripe's internal Ruby DSL directly.

The breaking point came in 2024 with the v2 namespace. v2 APIs are defined in a separate, Protocol Buffers-based DSL and serialized into snapshots by an internal API spec. That gave Stripe two formats, so every generator had to exist twice, CLI preview support for v2 was shut down, and the Shell did not support v2 at all, before v2 had even launched publicly. Stripe chose to converge on OpenAPI because it is the standard, already proven inside Stripe, and extensible.

The pipeline today:

  1. A generator reads both the v1 and v2 DSLs and produces OpenAPI documents controlled by three parameters:
    • Variant: which surface the artifact is for. The public stripe/openapi repository leaves out private metadata. Methods that only power the Dashboard never reach the public SDKs.
    • Phase: generally_available (GA only), public_preview (GA plus public preview) or private_preview (all three).
    • Version: which API version the document describes.
  2. Vendor extensions fill gaps in OpenAPI: x-stripeOperations lists the methods on a resource and drives SDK methods and CLI subcommands, x-resourceId names a resource, x-stripeResource gives type hints, x-stripeEvent marks event metadata (including whether it is a thin event, see Lesson 19), x-stripeAccess marks visibility, and x-expandableFields lists fields that can be expanded inline.
  3. Before merge, automated checks validate naming, field types, backwards compatibility and SDK-specific rules such as reserved words, and lint documentation (every public method, field and enum value needs a doc string). The PR shows an OpenAPI diff, and for v2 it also shows changes to past API versions, which catches accidental edits to history.
  4. After merge, a pre-release flow compares the previous and upcoming versions in an internal versioning tool, listing each change with SDK previews and suggested changelog text for product architects to review.
  5. At release, the canonical OpenAPI document is snapshotted and pushed to internal consumers, a CDN and open-source repos, then SDKs, CLI, reference and code samples are regenerated.

Overlooked constraints.

  • History must be reproducible. In v2 every API change is stored on disk, so Stripe can regenerate the exact API surface for any past date and improve old descriptions later. In v1 that is hard; Stripe stores a snapshot of the spec at each release, which means new metadata cannot be backfilled into older versions. The post names this as an unsolved problem.
  • One source of truth beats two good ones. Two well-built formats produced twice the generators and half the tool support.
  • Review happens at three points: design (the API review mailing list from Lesson 3), pre-merge (automated rules) and pre-release (product review in the versioning tool).

What Stripe sacrificed. Some expressiveness: OpenAPI cannot natively say everything Stripe's DSLs can, so Stripe maintains its own extensions and the tools that understand them. It also took on a large, permanent platform effort to keep two DSLs and their generators in parity.

Deep Dive: why the artifact matrix grows fast, and how generation tames itShow

Count the artifacts. With V variants, 3 phases and N supported API versions, the generator can emit up to V · 3 · N documents. With 5 variants and 40 versions that is 600 possible artifacts, each consumed by different tools. Written by hand, a single field rename would mean hundreds of edits; generated, it means one change in the DSL and one regeneration.

The same logic explains the pre-merge linter. A missing doc string or a reserved word (say, a field called class in a language where that is a keyword) is cheap to catch in the PR and expensive to catch after seven SDKs have shipped. Moving checks earlier, a principle called shift-left, trades a few seconds of CI time for avoiding a breaking SDK release that would itself need a version change module to undo.

Finally, a v2 diff that shows changes to past versions is a guard against a subtle class of bug: a refactor in shared code that silently changes what an old API version returns. Version change modules (Lesson 3) assume history is frozen. This check enforces it.

Lesson 5: Scaling your API with rate limiters#

Assumptions. The 2017 post assumes that traffic spikes are normal and come from four sources: one user's legitimate burst, one user's runaway or malicious script, a flood of low-priority requests (analytics) crowding out critical ones (charges), and internal failures that reduce capacity. It also assumes that most Stripe clients can slow down without harm: batch payment jobs can spread out. Where clients cannot slow down (true real-time events), rate limiting is the wrong tool and the answer is usually more capacity.

Production architecture. Stripe separates two ideas:

  • A rate limiter decides based on who is calling: this user has used up their allowance.
  • A load shedder decides based on the state of the whole system: the fleet is in trouble, so drop the least important work, no matter who sent it.

Stripe runs four of them, in order of how often they fire:

  1. Request rate limiter. Each user gets N requests per second. It is the most important one and fires constantly, rejecting millions of requests a month, many from test-mode scripts that got out of hand. Test and live modes behave the same, so code does not change behaviour when it goes to production. After studying traffic, Stripe added a short burst allowance for real-time events like flash sales.
  2. Concurrent requests limiter. "At most 20 requests in flight at once" instead of "1,000 per second". Expensive endpoints suffered when users retried slow calls, adding load to an already overloaded resource. This limiter fired about 12,000 times in the month described and, the post says, completely solved resource contention on CPU-heavy endpoints.
  3. Fleet usage load shedder. Traffic is split into critical methods (creating charges) and non-critical ones (listing charges). A Redis cluster counts in-flight requests of each type. A fraction of capacity is always reserved for critical traffic: with a 20% reservation, non-critical requests beyond their 80% share get HTTP 503.
  4. Worker utilization load shedder. The last line of defence. Traffic is split into four classes: critical methods, POSTs, GETs and test-mode traffic. When a server's workers back up, it sheds test-mode traffic first, then GETs, then POSTs, and brings traffic back slowly. It rejected only about 100 requests in the month described, but had shortened past incidents.

All limiters use the token bucket algorithm, backed by Redis: each user has a bucket, each request takes a token, tokens drip back at a fixed rate, and an empty bucket means rejection. The post's implementation advice is as important as the algorithms:

  • Fail open. If the limiter has a bug or Redis is down, requests must still be served. Catch every exception around the limiter.
  • Return the right error. 429 means "you, slow down". 503 means "we are overloaded". Messages should tell the user what to do.
  • Kill switches. Put every limiter behind a feature flag so a human can turn it off if it misfires, and alert on how often each fires.
  • Dark launch. Run each new limiter in a mode that only logs what it would block, tune it, and work with affected users before enforcing it.

Overlooked constraints.

  • Shedding must be slow in both directions. If a server sheds test-mode traffic, recovers, restores it all at once and collapses again, it flaps. Stripe tuned by trial and error to shed a substantial amount within a few minutes, not seconds.
  • Concurrency limits change the client's programming model. "Fork X workers that drain a queue" fits a concurrency limit. "Hammer and back off on 429" fits a rate limit. Choose what suits your users.
  • The limiter is a dependency on the hot path. A shared Redis cluster that every request consults must be both fast and optional, which is why fail-open is the first rule.
  • Priorities must be decided before the incident. The four traffic classes are a business decision (charges matter more than listings) encoded in advance.

What Stripe sacrificed. Some legitimate requests get rejected, especially bursts from well-behaved users, and test-mode users are the first to lose service in an incident. Failing open means that during a Redis outage there is no protection at all. Stripe accepted all three because the alternative, one user or one bad hour taking down the API for everyone, is worse for everyone, including the users being limited.

Deep Dive: token bucket math, fleet reservation and why shedding needs hysteresisShow

Token bucket. A bucket has capacity B and refills at r tokens per second. Over any interval of length t a user can send at most B + r·t requests. With r = 100/s and B = 200, a user can burst 200 requests instantly, then sustain 100/s. A one-minute flash sale at 150/s drains the burst in 200 / (150 − 100) = 4 s, after which about 50 requests per second get 429s. Raising B to 6,000 would let that user ride out the full minute. This is the "short burst allowance" in practice.

Implementing it in Redis. Store per user (tokens, last_refill_time). On each request: tokens = min(B, tokens + r · (now − last_refill_time)); if tokens ≥ 1, decrement and allow, else reject. Doing the read-modify-write in a single Lua script makes it atomic, so two servers cannot both spend the last token. One Redis round trip inside a data centre is typically well under a millisecond.

Fleet reservation. Suppose the fleet can handle 10,000 concurrent requests and 20% is reserved. Non-critical traffic may use at most 8,000 slots. Critical traffic can use all 10,000. In a normal hour non-critical traffic uses 3,000 and nothing is shed. If a slow database doubles every request's duration, Little's law (concurrency = arrival rate × time in system) doubles concurrency to 6,000, still fine. If it triples, non-critical traffic needs 9,000 slots, so 1,000 worth of list calls are shed and charges keep their 2,000-slot reserve.

Hysteresis. A controller that sheds when utilization is above 90% and restores when it falls below 90% will oscillate, because restoring load pushes utilization straight back over the line. Two standard fixes, both consistent with what the post describes: use different thresholds for shedding and restoring (shed above 90%, restore below 70%), and change the shed fraction in small steps over minutes. This is the same idea as a home thermostat that switches the heating on at 19°C and off at 21°C rather than toggling around 20°C.

Lesson 6: Advanced error handling patterns for enterprise integrations#

Assumptions. This 2024 post looks at rate limits from the client's side. It assumes a large integration will sometimes send bursts, for example a scheduled job that runs for thousands of connected accounts at once. Its stated limits: in live mode, up to 100 read and 100 write operations per second; in test mode, 25 of each; some resources such as the Files and Search APIs have stricter limits. Exceeding them returns HTTP 429.

Production architecture. The post uses Stripe Workbench, a developer panel inside the Dashboard, to diagnose the problem: its overview shows API request volume, versions in use and webhook activity; its Errors tab showed a spike of 429s caused by a monthly job creating metered-billing usage records for every customer at the same moment. It then layers three client-side patterns, each shown with a short Node.js example:

  1. Request spacing. Enforce a minimum gap between calls (the example uses the limiter library with one token per 600 ms).
  2. Concurrency control. Cap how many calls are in flight (the example uses p-queue with a concurrency of 5), combined with spacing.
  3. Token bucket. Allow bursts up to a bucket size while holding the average rate (the example: a bucket of 100 tokens refilled with 100 tokens every 60 seconds), again combined with a concurrency queue.

The Workbench chart in the post shows the before state (a red block of errors) and after state (a steady stream within limits).

Overlooked constraints.

  • Check the units. The spacing example's comment computes 60000 ms / 100 = 600 ms, which is 100 requests per minute, sixty times slower than the 100-per-second limit quoted in the same post. The token bucket example is also 100 per minute. That is a very safe setting for a demo, but a team that copies it to a large billing run would wait sixty times longer than needed. For 100/s with headroom, a spacing of about 12 ms (roughly 80/s) is closer to the real target.
  • Treat published limits as ceilings, not targets. The post says so directly: design to stay below them.
  • Limits are per account, not per process. Ten workers each spacing to 80/s send 800/s. A client-side limiter only works if it is shared (one process, or a shared store like Redis) or if each worker gets a fraction of the budget.
  • Spacing and retries interact. A 429 should be retried with backoff (Lesson 1) and should also consume budget in the shared limiter, or the retries themselves will cause the next 429s.

What Stripe sacrificed. Nothing in its own system; the post asks integrators to accept slower batch jobs and more code in exchange for fewer errors. That is the right trade-off for a platform: protecting the shared API from one account's cron job protects every other account too.

Deep Dive: sizing a client-side limiter for a monthly billing runShow

A platform has 30,000 customers and must post one usage record per customer at month end.

  • No limiter: 30,000 calls fired at once. At the 100 writes/s limit, everything beyond the first second's budget gets 429s. With retries and no jitter, the job repeats the spike several times.
  • Spacing at 600 ms (the post's demo setting): 30,000 × 0.6 s = 18,000 s, about 5 hours.
  • Spacing at 12.5 ms (80/s): 30,000 / 80 = 375 s, about 6 minutes, with 20% headroom left for interactive traffic on the same account.
  • Concurrency check: if a write takes 150 ms, sustaining 80/s needs 80 × 0.15 = 12 calls in flight (Little's law). A concurrency cap of 5 would limit throughput to 5 / 0.15 ≈ 33/s, so the cap, not the spacing, becomes the bottleneck. Always size spacing and concurrency together.

The lesson generalises: a rate limit is a budget of R per second, concurrency is R × latency, and a job of J calls takes at least J / R seconds. Write those three numbers down before choosing library settings.

Lesson 7: A rate-limit-friendly pattern for webhooks#

Assumptions. This 2025 guest post on Stripe's developer blog (by Phil Leggetter of Hookdeck, a webhook gateway company) starts from a popular pattern called fetch-before-process: treat each incoming webhook as a signal, then fetch the latest version of the object from the Stripe API before acting. The pattern exists because, at scale, webhook problems are not possibilities but guarantees: events arrive duplicated, out of order (an update before a create) and with stale or partial data. Fetching the current object sidesteps all three, and makes retries simple because a retry always fetches fresh data.

Production architecture. The catch is volume. A flash sale, a data migration or a monthly renewal run can produce thousands of events in seconds. If every event triggers an API read, the integration blows through the typical 100 reads/s limit and gets 429s. The post's pattern is to decouple ingestion from processing:

  1. All Stripe webhooks go to a gateway endpoint (Hookdeck in the post) that verifies Stripe's signature.
  2. The gateway queues events and delivers them to the application at a configured maximum rate (25/s in a sandbox, up to 100/s in live mode).
  3. The application verifies the gateway's own HMAC signature, then fetches the resource from Stripe and processes it. Because delivery is throttled, the fetch stays within limits.

The gateway shows queue depth and delivery delay, alerts when backpressure builds (the queue grows faster than it drains), and can retry failed events. Stripe's own signature check is still possible; the example disables Stripe's timestamp tolerance because the gateway already checked freshness and replays would otherwise be rejected.

Overlooked constraints.

  • A queue converts errors into delay. Throttling removes 429s, but every event behind the queue waits. The latency budget for "customer sees paid status" must allow for the worst backlog.
  • You still need idempotency. The gateway retries too. Processing must be safe to repeat, keyed on the event ID or the object's state.
  • The fetch doubles API use. Every event now costs one read. Thin events (Lesson 19) push this further by design: the event carries only an ID, so the fetch is mandatory.
  • Any durable queue works. The post uses a hosted gateway; the same shape can be built with SQS, Kafka or a database outbox. The key properties are durability, a rate-limited consumer and a dead-letter path for events that keep failing.

What the pattern sacrifices. Freshness of reaction (events wait in a queue), an extra moving part (the gateway or queue), and extra API reads. In return the integration gets correct ordering-independent processing and survives bursts without errors.

Deep Dive: backlog math for a renewal burstShow

A subscription business renews 60,000 subscriptions at midnight UTC. Stripe emits, say, three events per renewal (invoice created, finalized, paid): 180,000 events arriving over about 10 minutes, an average of 300/s.

  • Without a queue, the app would make 300 reads/s, three times the 100/s read limit. Two thirds of fetches fail, Stripe retries the webhooks later, and the retries collide with the next wave.
  • With a queue draining at 80/s, the backlog grows at 300 − 80 = 220 events/s for 600 s, peaking at 132,000 events. It then drains at 80/s, taking 132,000 / 80 = 1,650 s, about 27 minutes. The last event is processed about 37 minutes after midnight.
  • With fewer events to fetch. If the app only needs invoice.paid (60,000 events), the same queue finishes in 60,000 / 80 = 750 s, about 12.5 minutes, and never exceeds the read limit. Subscribing only to the events you act on is the cheapest optimisation.

If 37 minutes is too long for the business, the choices are: ask for a higher limit and raise the drain rate, use the webhook payload directly for events where staleness does not matter, or batch reads (for example list recent invoices once per second instead of fetching each). A queue makes the trade-off visible and tunable instead of leaving it to chance.

Lesson 8: Online migrations at scale#

Assumptions. The 2017 post by Jacqueline Xu describes moving hundreds of millions of Subscription objects to a new data model. It assumes three hard constraints. Scale: at one second per object, migrating 100 million objects one after another would take more than three years. Uptime: Stripe does all infrastructure changes online and has no maintenance windows. Accuracy: subscription logic spans thousands of lines across services, so a big-bang code change would certainly miss edge cases.

Production architecture. Early on, each Customer had at most one subscription, stored inside the Customer record. Later a Customer could have many, stored as an array inside the same record. Every subscription change then rewrote the whole Customer, and subscription queries had to scan customers. The fix was a separate Subscriptions table, reached with the classic four-phase dual-write pattern:

  1. Dual writing. Create the new table and write new subscriptions to both stores. Ramp the percentage of objects written twice slowly, watching database metrics, because the extra write is real load. Copy old objects lazily whenever they are updated. Then backfill the rest. Finding which objects needed copying was the expensive part, so Stripe did not query production. It used database snapshots loaded into Hadoop and a Scalding job (a Scala library for MapReduce) to list every subscription ID to copy, ran a parallel fleet of migration processes over that list, and ran the Scalding job again to confirm nothing was missing.
  2. Moving reads. Use GitHub's Scientist library to read from both stores in production, compare the results and alert on any difference. The experimental path cannot break the request: if it errors, the old result is still returned. Once results matched, reads moved to the new table.
  3. Moving writes. Reverse the direction: write to the new store first and mirror into the old one. Each code path that mutates subscriptions (updates, prorations, renewals) was isolated and changed separately, with more Scientist experiments. To catch forgotten callers, accessing the old subscriptions array was made to raise a hard error.
  4. Removing old data. Stop writing the old field, empty it lazily whenever a subscription is loaded, and run a final Scalding job and migration to clear the rest.

Overlooked constraints.

  • Backfill races with live writes. A backfill worker that read an object a minute ago can overwrite a newer copy made by the live dual write. Real backfills must write "only if absent" or compare versions or timestamps. The post's verification steps (re-running the Scalding job, Scientist comparisons) are how such races get caught.
  • Read checks need real traffic. Scientist compares results for the queries production actually runs, including odd ones nobody would think to test.
  • The unit of change is small. The post says Stripe never changed more than a few hundred lines of code at a time.
  • Observability is a precondition. Each step was safe only because a single inconsistent object raised an alert.

What Stripe sacrificed. Time and temporary complexity. For the length of the migration the codebase carried two data models, two write paths and comparison code, and the database carried extra writes. Stripe paid that cost to avoid both downtime and silent data corruption. See online data migrations for the general pattern and its variants (change data capture instead of dual writes, expand-and-contract schemas).

Deep Dive: backfill throughput and how long the migration really takesShow

Parallelism. At one second per object, 100 million objects take 100 million seconds, about 3.2 years, sequentially. With 1,000 parallel workers the same job takes 100,000 s, about 28 hours. But the real limit is not worker count. It is how much extra write load the production database can absorb without hurting live traffic. If the database can spare 2,000 extra writes per second, and each migrated object costs two writes (insert new row, mark old one), the backfill runs at 1,000 objects/s and takes about 28 hours regardless of how many workers exist. Throttling the backfill to the database's spare capacity, not to the worker fleet's size, is the safe default.

Why offline discovery matters. Finding candidates with a production query like "all customers with a non-empty subscriptions array" would scan the whole table, competing with live traffic. A snapshot in Hadoop turns that scan into an offline batch job with zero production impact. The same trick works with any data warehouse or a read replica dedicated to analytics.

Verification statistics. Suppose 1 object in 100,000 is migrated wrongly. Scientist comparing 1% of 50 million daily reads checks 500,000 reads a day. The chance of seeing zero mismatches in a day, if the bug rate per read is 10⁻⁵, is about e^(−5) ≈ 0.7%. So a day of clean comparisons gives strong evidence that the bug rate is below that level. Comparing on real reads is a statistical test, and its power grows with the sample.

Lesson 9: Document databases with 99.999% uptime and zero-downtime migrations#

Assumptions. The 2024 post describes DocDB, Stripe's database-as-a-service built on MongoDB Community. In 2023 Stripe processed $1 trillion in payments with 99.999% uptime. DocDB serves more than five million queries per second, with more than 10,000 distinct query shapes over petabytes of financial data in more than 5,000 collections on more than 2,000 shards. Stripe chose MongoDB in 2011 for developer productivity and the flexible document model. No managed MongoDB service met its needs then (MongoDB Atlas did not exist), so it built its own layer with these goals: top availability, durability and performance; a minimal set of database functions exposed to applications, to stop bad queries; horizontal scaling by sharding; first-class multitenancy with quotas; and enforced authorization.

Production architecture. Applications never talk to MongoDB directly.

  • A fleet of database proxy servers, written in Go, parses each query, enforces admission and access control, routes it to one or more shards, merges results and returns them.
  • A chunk metadata service maps chunks of each collection to shards, so the proxy knows where data lives.
  • Each shard is a replica set: one primary, several secondaries, replication and automatic failover.
  • Teams provision a logical database through a control plane; its collections are spread over many physical databases, each holding a small chunk.
  • Every write's change event flows through a change data capture (CDC) pipeline: each shard's oplog (MongoDB's log of every mutation) is shipped to Kafka and archived to object storage such as Amazon S3.

At the centre is the Data Movement Platform, built first to scale out past one machine's limits and later reused to merge underused shards, upgrade MongoDB versions and move big users from shared to dedicated shards. Its requirements were strict: data must stay consistent and complete; the critical step must be shorter than a normal primary failover (a few seconds, within applications' retry budgets); any number of chunk migrations must run at once, between any shards, for chunks of any size including terabytes; and the source shard must not slow down. A Coordinator runs six steps:

  1. Register the migration in the chunk metadata service and build indexes on the target shards.
  2. Bulk import a snapshot of the chunks taken at time T. Batching and engine tuning gave little gain. The breakthrough was inserting documents sorted by the most common index fields: because the storage engine keeps data in B-trees (balanced search trees stored in pages), sorted inserts touch neighbouring pages, which boosted write throughput about 10x.
  3. Async replication of every write since T, read from the CDC stream (Kafka and S3) rather than from the source shard, so it costs the source no read capacity and is not limited by the source's oplog size. The service tolerates target outages, can pause and resume from a checkpoint, reports its lag and replicates in both directions, tagging its own writes to avoid loops, so traffic can be switched back if the target misbehaves.
  4. Correctness check by comparing point-in-time snapshots, again to avoid load on live shards.
  5. Traffic switch using versioned gating (below), in under two seconds.
  6. Deregister the migration and drop the chunk from the source.

The traffic switch is the delicate part. Every proxy stamps its requests with a version token. A custom MongoDB patch makes each shard reject requests whose token is not newer than the one it knows. To move a chunk:

In 2023 the platform bin-packed thousands of underused databases, moving 1.5 petabytes invisibly to applications and cutting the number of shards by about three quarters. It also upgraded the fleet to a newer MongoDB major version in one step by copying data to new shards, skipping the chain of in-place upgrades. Next on the list: a heat management system to rebalance shards by size and throughput, and shard autoscaling.

Overlooked constraints.

  • The proxy is what makes migrations transparent. Applications see one logical database; only the proxy and the metadata service know about chunks. Without that indirection, every migration would need application changes.
  • Downtime is defined by the retry budget. The switch blocks traffic to the chunk for a moment. That is acceptable only because it is shorter than a failover and clients already retry through failovers.
  • Bidirectional replication is the rollback plan. A one-way copy can only go forward.
  • Never read the source to copy it. Using the CDC stream protects live query capacity.
  • Exposing a small set of database functions limits what applications can do (no arbitrary queries), which is what keeps 10,000 query shapes manageable.

What Stripe sacrificed. It owns a large, custom database platform, including a patch to MongoDB itself, a proxy fleet, a metadata service and a replication service, instead of using a managed product. Applications give up direct database access and some query flexibility. Each traffic switch costs a short burst of rejected requests that must be retried.

Deep Dive: what five nines means, and why sorted inserts are ten times fasterShow

The five-nines budget. 99.999% availability allows 0.001% downtime: 525,600 minutes × 0.00001 ≈ 5.26 minutes per year. If each chunk switch blocks a chunk for 2 s, and a chunk holds a small share of traffic, the cost to overall availability is tiny. For example, 10,000 switches a year, each blocking 0.05% of traffic for 2 s, add up to 10,000 × 2 s × 0.0005 = 10 s of full-API-equivalent downtime a year, and even that is hidden by retries. A migration design that needed a 10-minute pause per shard would blow the year's budget in one go.

B-tree locality. A B-tree stores keys in sorted pages, typically a few kilobytes to tens of kilobytes each. Inserting keys in random order lands each insert on a random leaf page. If the index is larger than memory, most inserts read a page from disk, modify it, and later write it back, and pages split all over the tree. Inserting in sorted order appends to the rightmost leaf over and over: the same page stays in cache until it fills, splits happen only at the edge, and pages are written once, full. With 100 documents per page, random order can cost up to one page read per insert, while sorted order costs about one page write per 100 inserts. A 10x gain is well within that range.

Bin packing. Merging small databases onto fewer shards is a bin-packing problem: each database has a size and a throughput, each shard has capacity in both. Classic heuristics such as "first fit decreasing" (sort items largest first, place each in the first shard with room) get close to optimal. Cutting shards by three quarters means the average shard was running at roughly a quarter of its useful capacity before. Online migrations are what made the packing safe to do.

Lesson 10: Fast and flexible observability with canonical log lines#

Assumptions. The 2019 post by Brandur Leach assumes that logs are the most flexible observability tool, because they record far more than anyone planned to ask about, but that they are slow and awkward to query when one request's facts are spread over many lines. Metrics dashboards (Graphite and statsd in the post) are fast but only answer questions designed in advance.

Production architecture. First, structured logging: lines carry key=value pairs (often called logfmt) so machines can parse them and people can still read them. Then the key idea: in addition to normal logs, every request emits one long line at the end with all of its important facts. Stripe calls it the canonical log line, "canonical" in the sense of authoritative, like a canonical URL. A typical line holds:

  • HTTP method, path and response status.
  • The authenticated user, how they authenticated (API key or password) and the key ID.
  • Rate limiter results: allowed or not, quota and what remains.
  • Timing: total duration and time spent in the database.
  • Counts: database queries issued, objects allocated by the Ruby VM.
  • Team and permission information.

Questions that needed a join across lines become one filter. "Which users are rate limited most?" is canonical-log-line rate_allowed=false | stats count by user_id. If one user dominates, the limit is working. If many users appear, there is probably a bug. Latency for one user's charges, excluding fast-failing 4xx errors that would distort it, becomes one timechart of p50, p95 and p99.

The implementation is a middleware in the API stack. Code that runs during the request adds fields to the request environment; the middleware reads them after the request finishes and writes the line. It runs in Ruby's ensure block, so the line is written even when an exception is unwinding the stack. The logging call has its own begin/rescue, so a bug in building the line never fails the request, and it alerts someone, because losing these lines would be "flying blind". Stripe emits canonical lines everywhere: the API, every webhook sent, every card tokenized by the PCI vault, every Dashboard page load.

The lines then became a data product. Stripe fixed the field names in a protocol buffer schema, because engineers had memorised them and renames hurt. Each line is also sent asynchronously to Kafka, batched into S3, and loaded into Presto and Redshift for long-term SQL analysis, such as tracking which Go versions API clients use, by anyone in the company. The same archive, processed by MapReduce, draws the request charts in the user-facing Developer Dashboard, and the schema keeps those charts from breaking. For others the post sketches a pipeline: local log agents such as fluentd shipping to Elasticsearch, Stackdriver or CloudWatch for search, and Kafka (or Redis streams at small scale) feeding Redshift or BigQuery for warehousing.

Overlooked constraints.

  • The line must survive failures. The requests you most want to see are the ones that crashed. Writing in ensure is the whole point.
  • Field names are an API. Once dashboards, queries and products depend on them, renames are breaking changes, hence the protobuf contract.
  • Emit asynchronously. Sending to Kafka must never slow the user's request.
  • Cardinality is fine here. Logs can hold user IDs and request IDs, which would explode a metrics system's time-series count.

What Stripe sacrificed. Some duplication and storage: the same facts appear in normal log lines and in the canonical line. Canonical lines are also slower to query than pre-computed metrics. Stripe accepted both because the lines give flexible answers during the confusing first minutes of an incident and double as cheap long-term history. The observability page covers how this idea relates to "wide events" and tracing.

Deep Dive: why one wide line beats five narrow onesShow

Query cost. Suppose each request writes 5 log lines, and a question needs fields from two of them (say rate_allowed from line 3 and user_id from line 2). The log system must find both lines for every request and group them by request_id, which is a join over the whole time range. At 5,000 requests/s, one hour is 18 million requests and 90 million lines, all scanned and grouped. With canonical lines the same question is a filter and group-by over 18 million lines with no join. Grouping by request ID needs memory proportional to the number of distinct requests in flight in the query, which is exactly what makes multi-line queries slow and sometimes impossible on large ranges.

Storage math. A canonical line of about 1 KB at 5,000 requests/s is 5 MB/s, or about 430 GB a day before compression. Text logs typically compress 5x to 10x in columnar formats, so roughly 45 to 90 GB a day, cheap enough to keep months of history in S3 and query with Presto. Full verbose logs at 10 to 20 lines per request are an order of magnitude larger, which is why the post says long-term retention of ordinary logs is expensive and rarely worth it.

Logs versus metrics. A metric like api.requests{endpoint, status} is tiny and fast but cannot answer "which user?" without adding a user_id tag, which would create one time series per user. Canonical lines carry high-cardinality fields for free because each line is an independent record. Use metrics for alerts and fast dashboards; use canonical lines for questions you did not know you would ask.

Lesson 11: Veneur, high-performance global aggregation for Datadog#

Assumptions. In 2016 Stripe moved its metrics to Datadog, a hosted metrics, dashboard and alerting service, because its previous open-source stack was unowned internally and costly in people and money. It instrumented code in the StatsD style: each event sends a small text message over UDP (a "fire and forget" network protocol with no delivery acknowledgement) to a collector. The post names StatsD's two problems for Stripe: UDP packets can be silently dropped, and a central StatsD server is a single point of failure that must handle huge packet volumes. Datadog's answer is DogStatsD, an agent on every host. That fixed performance but removed global percentiles: histograms and timers were aggregated per host only.

Production architecture. Stripe needed the p99 of an API endpoint across all hosts, not per host. Percentiles cannot be combined after the fact: if host A's p99 is 8 ms and host B's is 10 ms, the overall p99 is unknown, and the post notes it can even be higher than every host's own p99. The only correct method is to combine the underlying samples.

Veneur (named after the Grand Huntsman of France, master of the royal hounds) is Stripe's open-source DogStatsD server, written in Go:

  • It runs on every host in place of the bundled DogStatsD, on the same port, so applications change nothing.
  • Counters and other simply combinable values are flushed straight to Datadog.
  • Histograms are not turned into percentiles locally. They are forwarded to a global Veneur instance that merges histograms from every host and flushes true global percentiles one flush period later.
  • To keep the global instance's memory bounded, histograms are stored as t-digests, compact approximate summaries that use constant space whatever the number of samples (Stripe wrote its own Go port).
  • Sets (count of unique values) use HyperLogLog, a fixed-memory approximate distinct counter, and are forwarded too.
  • Flushes to Datadog are compressed, chunked and concurrent, and Veneur reports extensive metrics about itself.

Degradation was designed in. The global instance is a single point of failure for percentiles and sets, but count, minimum and maximum can be combined without it (the global maximum is the maximum of host maxima) and are reported locally right away. If the global instance dies, Stripe loses global percentiles, not all metrics. Clients can also opt out of forwarding.

Overlooked constraints.

  • Smart clients were a dead end. Stripe tried client libraries that routed each metric to the right place. Supporting that in every language undermined StatsD's best feature: you can instrument something with a bare nc command.
  • Raw speed was not the goal. The first version was a very fast global DogStatsD with no forwarding. Processing more packets did not solve the real problem, correct global aggregates.
  • Users adapt to whatever you ship. When Stripe temporarily fell back to per-host metrics during a refactor, teams that had just switched to global percentiles broke.

What Stripe sacrificed. Exactness and freshness: t-digest percentiles carry a small error, and global percentiles arrive one flush interval late. It also took on owning a piece of its metrics pipeline instead of using the vendor's agent as shipped.

Deep Dive: why you cannot average percentiles, and how t-digest makes merging possibleShow

A worked counter-example. Host A serves 9,900 fast requests in a minute with p99 = 8 ms. Host B serves 100 requests, all to a slow reporting endpoint, between 300 and 400 ms, so its p99 is about 400 ms. Across both hosts there are 10,000 requests, and the slowest 1% (100 requests) are exactly host B's. The true global p99 is therefore about 300 ms, the fastest of B's requests. The plain average of the two p99s is 204 ms. A request-weighted average is 0.99 × 8 + 0.01 × 400 ≈ 12 ms. Both are wrong, and the weighted one is wrong by a factor of 25. Only merging the distributions gives the right answer.

t-digest. Ted Dunning and Otmar Ertl describe the t-digest in "Computing Extremely Accurate Quantiles Using t-Digests" (2019). It summarises a distribution as a list of centroids (a mean and a count). Centroids near the middle of the distribution may hold many samples; centroids near the tails are kept small, so the extremes (p99, p99.9) stay accurate. A few hundred centroids, a few kilobytes, can summarise billions of samples with typical tail errors well under 1%. Two digests merge by pooling their centroids and re-compressing, which is exactly what the global Veneur does.

HyperLogLog. Philippe Flajolet and co-authors described HyperLogLog in 2007. It hashes each value and tracks, in each of m registers, the longest run of leading zeros seen. With m = 2^14 registers (about 12 KB) it estimates the number of distinct values with about 0.8% standard error, whether there are thousands or billions. Two HyperLogLogs merge by taking the register-wise maximum, so per-host sets combine exactly as cleanly as maxima.

Cost of global aggregation. If 1,000 hosts each forward 2,000 histograms every 10 s, and each digest is about 2 KB, the global instance receives 4 GB per flush, 400 MB/s. That is why the design keeps digests small and lets counters bypass the global tier entirely: only metrics that truly need merging pay the forwarding cost.

Lesson 12: The secret life of DNS packets#

Assumptions. DNS, the system that turns names into IP addresses, is a prerequisite for almost every network call, so a DNS problem quickly becomes a company-wide outage. The 2019 post by Jeff Jo assumes that DNS must be instrumented as carefully as any application, because when it fails, the error it returns tells you almost nothing.

Production architecture. Stripe ran a cluster of DNS servers using Unbound, an open-source recursive and caching resolver. Unbound forwarded queries by domain: service-discovery names went to Consul, and names in Route 53 plus the public internet went to the VPC resolver that AWS provides inside each virtual network. Every host also ran a local Unbound as an extra cache. Unbound's statistics (query counts, types, cache hit ratios) fed the metrics pipeline.

The incident: for a few minutes every hour, the DNS servers returned SERVFAIL (a generic "something went wrong" DNS answer) to a small share of internal requests. Query volume and resource use looked normal. The clue was Unbound's request list depth, its internal to-do list of queries waiting to be resolved, which spiked. The investigation went step by step:

  1. unbound-control dump_requestlist showed the list was full of reverse lookups (PTR records, which map an IP back to a name), all waiting on the VPC resolver.
  2. tcpdump, writing one capture file per 60 seconds so files stayed small, showed that during spikes 90% of queries to the VPC resolver were reverse lookups for addresses in 104.16.0.0/12, mostly failing.
  3. The queries came from the Hadoop cluster. Matching job start times against the spikes found one hourly job that reverse-resolved every IP in network activity logs.
  4. In one 60-second capture the DNS server sent 257,430 packets to the VPC resolver and got back 61,385, about 1,023 per second, right at AWS's limit of 1,024 packets per second per network interface for the VPC resolver.
  5. To confirm, Stripe added an iptables rule matching traffic to the VPC resolver's address (always the VPC base address plus two, such as 10.0.0.2), read its packet counter every second and reported it as a metric. The SERVFAIL spikes lined up with the packet-rate ceiling.

The packets also revealed amplification: each host's local resolver timed out and retried a failed reverse lookup five times, and the DNS servers retried as well, multiplying traffic by about 7x on average.

The fix used the fact that the limit is per interface. Stripe configured the local Unbound on Hadoop hosts to forward the reverse zone (in-addr.arpa) directly to the VPC resolver, spreading the load across many interfaces instead of funnelling it through a few DNS servers. It used two forwarding rules, one for private addresses (10.in-addr.arpa, answered quickly from Route 53) and one for all other reverse lookups. Unbound computes retry timeouts from a smoothed average of past round-trip times, separately per rule, so slow public lookups no longer inflated timeouts for fast private ones. The hourly spikes disappeared.

Overlooked constraints.

  • Cloud limits hide in the fine print. The 1,024 packets-per-second limit is per interface, invisible to normal metrics and enforced by silently dropping packets.
  • Retries at two layers multiply. The same arithmetic as in the AWS lesson on retries: 5 client retries times server retries made a slow upstream into a saturated one.
  • Batch jobs live on the same infrastructure as payments. An analytics job doing reverse DNS took down name resolution for production requests.
  • Separate timeouts per destination. Mixing fast and slow queries in one round-trip estimate degrades both.

What Stripe sacrificed. Some simplicity: Hadoop hosts now bypass the central resolvers for reverse lookups, so DNS behaviour differs by host role and by zone. Stripe also took on custom instrumentation (the iptables counter) and was considering rolling packet captures, extra operational cost in exchange for faster diagnosis next time. See the DNS page for how resolvers, caching and TTLs fit together.

Deep Dive: packet budgets and why spreading across interfaces worksShow

Reading the capture. 257,430 packets sent in 60 s is 4,290 per second. 61,385 answered in 60 s is 1,023 per second. So about 76% of queries were dropped by the resolver's rate limit. Each dropped query was retried, which added to the 4,290, which kept the drop rate high: a classic retry storm on a hard cap.

Back out the real demand. With about 7x amplification, 4,290 packets/s of offered traffic corresponds to roughly 600 unique lookups per second from the job. One central server's interface can carry 1,024/s. If there were, say, three DNS servers sharing the load, the cluster's ceiling would be about 3,000/s, still below 4,290. Spreading the same 600 unique lookups over 200 Hadoop hosts gives each host 3 lookups per second, a tiny fraction of its own 1,024/s budget. Even with retries, no interface comes close to the limit.

Why caching did not save it. Reverse lookups for many different public IPs rarely repeat within a TTL, so the cache hit ratio for this workload is low. Every lookup goes upstream. Workloads with high-cardinality keys defeat caches, and the caching fundamentals page explains why hit ratio depends on key reuse.

A better job design. The handbook's suggestion, not from the post: deduplicate IPs within the job before lookup, cache results across runs in a table, and rate-limit lookups per host. A job that resolves 600 IPs/s every hour probably sees the same IPs again and again.

Lesson 13: Building a data plane from scratch, Stripe's own distributed proxy#

Assumptions. The 2026 post says a failed payment means a Stripe user did all the work to win a customer and lost the sale because of Stripe. Stripe targets 99.9995% reliability while processing about 1.6% of global GDP. Internal services talk through a service mesh: a layer of proxies next to each service that handles routing, load balancing, authorization and encryption. This mesh carries millions of requests per second between thousands of services, and each public API call fans out into many internal calls, so small proxy improvements matter a lot.

Production architecture. For almost ten years Stripe used Envoy, a widely used open-source proxy. Three problems grew with scale:

  • Connection cardinality. Envoy's model runs one worker per CPU core, and under steady traffic each worker usually keeps a connection to every upstream it can route to. Two 8-core clients talking to two servers produce 16 connections per server. A fleet-wide service such as one that collects tracing data ends up holding roughly one connection per CPU core in the whole fleet, hundreds of thousands of connections, which is expensive and has caused incidents.
  • Risky upgrades. Hyrum's Law says that with enough users, every observable behaviour of a system will be depended on by somebody. With many unique services, small behaviour changes in Envoy releases broke things. In 2024 an Envoy upgrade pulled in a new nghttp2 library with a defence against the HTTP/2 rapid reset denial-of-service attack. With default settings, that defence rejected some legitimate traffic to one service. A QA load test caught it; production might not have.
  • Customization limits. Stripe had designed better routing for its expensive Ruby backends but could not build it inside Envoy without too much customization.

Stripe built mesh-proxy in Go, with its own HTTP/1.1 and HTTP/2 implementations, direct integration with the service registry (instead of Envoy's xDS configuration API, which had sent far more updates than needed and burned CPU and memory), and support for retries, hedging (sending a duplicate request when the first is slow), rate limiting and priority-based routing. Its concurrency model is one read goroutine and one write goroutine per connection, with requests multiplexed over one shared connection per host. Goroutines are cheap enough to spawn per connection, Go's official HTTP/2 framing library helped, and Go is well supported inside Stripe.

Results reported in the post: about half the CPU under high load, roughly a 50% latency reduction compared with the Envoy deployment, about 3,000 days of cumulative inter-service latency saved per day, a large drop in CPU and memory on services that had been flooded with xDS updates, and 15 to 20% more headroom on Ruby backends thanks to custom load balancing. An overhaul of priority-based routing also improved deployments, rate limiting and traffic shifting.

Overlooked constraints.

  • Building your own is a bet on your team. The biggest risk was not matching Envoy's latency and CPU; early load tests had to prove it. Every line is reviewed by the team and tested with unit, end-to-end and synthetic tests.
  • Shared connections need shared state. Multiplexing many requests over one connection means coordinating request state across goroutines, which the post names as the main extra complexity.
  • Load tests must look like production. The rapid-reset regression was caught only because the load test matched that service's traffic shape.
  • The data plane sees everything. Owning it gives a unique view for anomaly detection and smart routing, which the team is now building.

What Stripe sacrificed. The community, documentation and security patching of a widely used open-source project. Stripe now owns HTTP/2 correctness, every edge case of the protocol and every future vulnerability fix itself. It judged that worth it because its mesh had become custom enough that the off-the-shelf proxy was the bigger risk.

Deep Dive: connection counts, five and a half nines, and what 3,000 days a day meansShow

Connection math. With Envoy, a server receives about Σ cores connections from its clients, one per client worker. With 5,000 client machines of 32 cores each, a fleet-wide service sees up to 160,000 connections per instance. With one multiplexed connection per client host it sees 5,000, a 32x reduction. Each idle TLS connection costs memory (tens of kilobytes for buffers and TLS state), so 160,000 connections can mean several gigabytes per server before a single request is served.

The budget. 99.9995% availability allows 0.0005% failure: about 2.6 minutes per year, or 1 failed request in 200,000. A single incident like the rapid-reset rejection, if it reached production for even a few minutes, would consume the whole year's budget. That is why upgrade risk, not raw performance, drove the decision.

Latency saved. 3,000 days is 3,000 × 86,400 ≈ 259 million seconds of latency saved per day. If mesh-proxy saved about 1 ms per call, that implies roughly 2.6 × 10¹¹ calls a day, around 3 million calls per second, consistent with "millions of requests per second". The figure sounds abstract, but it compounds: a public request that makes 20 internal calls in sequence gains 20 ms of end-to-end latency.

Why hedging belongs in the proxy. Hedging sends a second copy of a request if the first has not answered within, say, the p95 latency, and uses whichever answers first. If calls are independent and the p99 is 10x the p50, hedging at p95 costs about 5% extra load and cuts the tail sharply. It is only safe for idempotent calls, which is one more reason idempotency (Lesson 1) shows up everywhere at Stripe. Jeffrey Dean and Luiz André Barroso describe the technique in "The Tail at Scale" (Communications of the ACM, 2013).

Assumptions. The 2026 post opens at 2 a.m.: a MongoDB shard, one of 2,000 that together handled $1.9 trillion in payments in 2025, is degraded. Two nodes are down and a third blocks an index build because of a misconfigured vote. An engineer needs about 15 minutes to plan the order of manual steps and up to 3 hours to run and watch them. This happened hundreds of times a year across more than 40 shard layouts, from cheap configurations to high-availability ones built for disaster recovery. The number of failure combinations was too large for hand-written automation.

Production architecture. The first system (V1) was a set of single-issue plugins ("fix votes", "fix priority", "rebuild downed node") run in a fixed priority order inside a reconciliation loop. It failed in four ways: hidden dependencies between plugins (the vote and priority fixers required no nodes to be down but ran before the node-down fixer, a circular wait only a human could break); multi-failure blind spots; layout-specific checks in every plugin, so each new layout took about a week to onboard; and cancelled workflows leaving shards in states no plugin expected. In one six-month window it paged operators 124 times for misconfigured shards and 32 times for node-down cases complicated by other problems, and blocked index builds and maintenance for about an hour per incident.

The breakthrough was a change of question. Not "what is the most important thing to fix now?" (a greedy, local choice) but "what sequence of operations turns the current state into the healthy state without ever breaking a safety rule?" That is a graph search.

  • States are snapshots of a shard: per-node votes (participation in elections and write quorum), priority (eligibility to become primary) and hidden status (out of the client read path), plus shard-wide facts like oplog size, regional spread and quorum status.
  • Edges are atomic operations: add or remove a vote or priority, hide or unhide a node, rebuild a node, resize the oplog.
  • The start is the observed "ground reality". The goal is the shard's declared source of truth (SOT).
  • Invalid states break invariants and are pruned: an even number of votes, healthy voters in the minority (write availability at risk), or a node with priority 1 but no vote.

Breadth-first search (BFS) explores states level by level, so the first path that reaches the goal uses the fewest operations. In the post's example (a data node down, the backup down, and another data node missing its vote and priority) V1 is stuck, but BFS finds three valid orderings. Fixing the vote and priority first is safe because it keeps quorum, and it unlocks the rebuilds.

Simulation that is the real code. Remediation steps are Temporal workflows and activities. Temporal is a durable execution framework: a workflow interrupted by a deploy or crash resumes where it left off, which matters for node rebuilds that take hours. But those steps make real network calls, so running them to explore thousands of states would take forever. Stripe added a CommonContext interface that is backed either by Temporal's real context or by an in-memory implementation in which operations are pure state transformations. Planning and execution run the same business logic: what is simulated is what is executed. Minutes of I/O become milliseconds of CPU, and the planner explores hundreds of transitions per second.

From BFS to Dijkstra. BFS fails completely when the full goal is unreachable, for example when an extra node cannot be reached by automation but a missing vote could easily be fixed. Stripe moved to Dijkstra's shortest-path algorithm on a weighted graph:

edgeWeight(state, op) = misconfiguration(state) × estimatedTime(op)

misconfiguration is a sum of composable rules (down nodes, voting, priority, oplog size, hidden status, availability-zone imbalance). estimatedTime uses relative costs: a config update is 3, an oplog resize 19, a node rebuild 101 (about 33 times a config change). Multiplying the two means the planner minimises time spent misconfigured: quick fixes that cut risk go first, long rebuilds later. Because Dijkstra finds paths to every reachable state, when the goal is unreachable it returns the path to the least misconfigured state, giving partial remediation and leaving only the truly stuck part for a human.

Results: about 30% fewer pages (around 200 a year), 12 fewer days a year of shards stuck unhealthy, zero code changes to support a new layout, and safe recovery after cancelled workflows (just plan again from wherever the shard is). Future plans: use the same planner for layout changes (set a new goal and let it find a safe path), blue-green version rollouts, and batching maintenance when a node is already offline.

Overlooked constraints.

  • Fidelity is everything. A planner whose model differs from reality will propose plans that fail or harm. Sharing one codebase for simulation and execution is the guard.
  • Invariants must be complete. The search is only as safe as the rules that prune bad states.
  • Greedy fixes create deadlocks. "Fix the highest priority issue first" is exactly how V1 got stuck.
  • The state space must stay small. Per-shard state with a handful of nodes keeps search fast; a model of the whole fleet would not be searchable.

What Stripe sacrificed. Predictability of the exact steps: the automation now discovers sequences no human wrote down, so engineers trust invariants and logs rather than a runbook. It also had to model shard state precisely enough to simulate, which is a large investment in abstraction (the CommonContext layer) on top of Temporal.

Deep Dive: why the search is cheap, and a worked Dijkstra exampleShow

State space size. A shard with 5 nodes, each with vote (0 or 1), priority (0 or 1), hidden (0 or 1) and health (up or down), has 2⁴ = 16 combinations per node and 16⁵ ≈ 1 million raw states. Most are invalid and pruned immediately, and BFS from a near-healthy state usually finds the goal within 3 to 6 steps. With a branching factor of about 10 operations per state, depth 5 is at most 10⁵ states, and in practice far fewer survive pruning. At hundreds of transitions a second, even the worst case takes minutes, and typical cases take well under a second.

A worked example of the weighted search. Start with a misconfiguration score of 10 (say 6 for a missing vote, 4 for a down node). Two orders are possible.

  • Rebuild first: weight = 10 × 101 = 1,010. The shard is now at score 6. Then fix the vote: 6 × 3 = 18. Total 1,028.
  • Fix vote first: weight = 10 × 3 = 30. Score is now 4. Then rebuild: 4 × 101 = 404. Total 434.

Dijkstra picks the second order. The weighting expresses a simple principle: the cost of a step is how long you stay exposed while doing it, so do quick risk-reducing fixes before long ones.

BFS versus Dijkstra. BFS minimises the number of steps and ignores how long each takes or how risky the waiting is. Dijkstra minimises total weight, with all weights non-negative, which is the condition Dijkstra's algorithm needs (Edsger Dijkstra, "A note on two problems in connexion with graphs", 1959). Because Dijkstra settles states in order of cost, the cheapest-to-reach least-misconfigured state is available even when the full goal never appears, which is what makes partial remediation fall out naturally.

Lesson 15: Root cause analysis of the 2019-07-10 API degradation#

Assumptions. Stripe's CTO, David Singleton, published this analysis two days after the incident. The setting: data is split by kind into clusters and by quantity into shards; each shard has several redundant nodes; failover is exercised routinely during upgrades, maintenance and failures. Stripe assumed that a database version that had run correctly for three months, through many failovers, was safe.

What happened. On 2019-07-10 the Stripe API was severely degraded from 16:35 to 17:02 UTC and again from 21:14 to 22:47 UTC. A substantial majority of API requests failed in those windows. The causes were two database bugs and a configuration change interacting in an unforeseen way.

  • Three months before: a new database minor version, tested in QA and rolled out in phases from less to more critical clusters, introduced a subtle fault in the failover system that only appeared when several nodes were stalled.
  • Four days before: two nodes stalled for reasons not yet known. They stopped reporting replication lag metrics but kept answering active health checks as healthy.
  • 16:35: the primary of one shard failed. The shard could not elect a new primary, so it could not accept writes. Because many applications, including the API, used that shard, their writes timed out, compute resources were starved, and the failure cascaded across the API.
  • 16:36: alert and incident response (detection within one minute, response within two).
  • 16:50: the team determined that the cluster could not elect a primary.
  • 17:00: restarting all nodes in the cluster forced a successful election. Recovery at 17:02, 27 minutes after the start.
  • 20:13 to 20:42: investigating, the team found a likely bug in the new version's election protocol and rolled every shard in the cluster back to the previous version, deployed within four minutes.
  • 21:14: high CPU in the cluster; the API failed again. The team assumed the first problem had returned on more shards and applied the same playbook.
  • 21:26: the real cause was different: the rolled-back election protocol interacted badly with a recently introduced configuration setting, starving CPU on every affected shard. Applying the fix was slowed by that same CPU contention.
  • 22:34: new configuration rolled out and nodes restarted. Traffic was ramped back up, prioritising services that serve user-initiated API requests. Full recovery at 22:47.

Remediations announced.

  • Alert when nodes stop reporting replication lag, and when a shard enters a state that could trigger the election fault; work with the database maintainers on a fix.
  • Stop single-shard failures from cascading: more circuit breaking on failed operations to particular clusters, more fault isolation to contain one failed shard, and limits on resources consumed by clients retrying failed requests.
  • New procedures and tooling to make rapid configuration changes during incidents safer.

Overlooked constraints.

  • Health checks can lie. The stalled nodes passed active checks. The real signal was an absence: metrics that stopped arriving. Monitoring for missing data is as important as monitoring for bad data. This kind of partial, hidden failure is often called a gray failure.
  • Latent bugs wait for rare states. Three months and many successful failovers did not exercise "multiple stalled nodes". Phased rollouts reduce blast radius, but they cannot test states that have not happened yet.
  • The fix can be the second incident. The rollback was a change made under time pressure, and it met a configuration nobody had tested it with. Same symptoms, different cause, so the same playbook did not apply.
  • Shared dependencies turn one shard into a company-wide outage. Without isolation, threads waiting on one shard's writes consumed resources the whole API needed.

What Stripe sacrificed. The incident itself cost two hours of severe degradation. The remediations trade throughput and simplicity for isolation: circuit breakers and per-cluster limits will fail some requests fast that might eventually have succeeded, and slower, more controlled config changes slow down future incident response in exchange for fewer self-inflicted second waves. Read with incident management and postmortems.

Deep Dive: the availability arithmetic of one bad day, and how isolation would have changed itShow

Budget. The two windows lasted 27 and 93 minutes, 120 minutes in total. At 99.999% the yearly budget is about 5.3 minutes; at 99.99% it is about 53 minutes. One day consumed more than two years of a four-nines budget, which shows why Stripe's later posts (Lessons 9, 13 and 14) chase faster failover, smaller blast radius and automated remediation.

Cascades through thread pools. Suppose an API server has 200 worker threads, 5% of requests write to the failed shard, and each such write now waits for a 30-second timeout instead of 10 ms. At 1,000 requests/s per server, 50/s hang for 30 s, so by Little's law about 1,500 threads would be needed just for the stuck requests. The pool of 200 fills in about 4 seconds, and from then on every request, including the 95% that never touch the shard, waits for a free thread. That is "starved compute resources" in numbers. A per-dependency concurrency limit (say, at most 20 threads waiting on that cluster) or a circuit breaker that fails those writes in milliseconds keeps 180 threads free and limits the impact to the 5% that genuinely needs the broken shard. The resilience patterns page covers bulkheads and circuit breakers in depth.

Why the absence of metrics matters. A health check asks "are you alive?". A stalled replica says yes. Replication lag metrics answer "are you making progress?". The best health signal for a replica is not a ping but progress: is its applied position advancing? Alerting when a progress metric goes silent catches exactly the stall that preceded this incident.

Lesson 16: Ledger, the double-entry system that proves money movement is correct#

Assumptions. Stripe connects to local banks and networks in 185 countries and supports more than 135 currencies and payment methods. Every partner has its own interface, data model and reporting cadence. Some internal systems emit billions of events per day; others emit a few hundred per month. Each team has its own idea of "correct". The design assumption is that the real world is imperfect, incomplete and changing: partner reports arrive malformed, a currency can stop existing, a large bank can collapse overnight. The goal is therefore not "no errors" but "every error is bounded, visible and explainable". The post (Ilya Ganelin, 2024) gives the scale: in the Black Friday to Cyber Monday window Stripe processed 300 million transactions worth $18.6B while the API stayed above 99.999% availability, and Ledger ingests about five billion events per day.

Production architecture. Ledger is an immutable, auditable log that acts as the system of record for all financial data. It does two things.

  1. Models producers as state machines. Each producer system (charges, payouts, currency conversion, report parsing, billing estimation) is encoded as a fund flow: events move balances between accounts, and the accounts are the states. An account is a bucket identified by a type (for example charge_unsubmitted or charge_undisbursed) plus properties (for example the charge id and the business). An event (for example charge.creation, charge.release) moves an amount from one account to another.
  2. Computes every balance. Ledger sums balances across every account type and every property subdivision, and uses those sums as health statistics.

Because Ledger records the actual work of each producer as transactions, rather than deriving a dataset from a pipeline, instrumenting Ledger indirectly instruments every upstream pipeline. When something is wrong, Ledger can tell the owning team which step of their pipeline broke.

A charge is the simplest example. At T0, charge.creation puts the amount into a charge_undisbursed account for business A and charge id 123. At T1, charge.release moves it into business_balance for business A. The two events are independent: they can arrive out of order and come from different sources, because Ledger matches them by the account properties (business and id), not by arrival order. If the release never arrives, or carries the wrong id, the charge_undisbursed balance for that charge stays non-zero.

The three Data Quality metrics. On top of Ledger sits the Data Quality (DQ) Platform. For any slice of data evaluated at time X it asks three questions.

  • Clearing. Did the fund flow complete? This rests on double-entry bookkeeping: every movement is a debit in one account and an equal credit in another, so the total across the system always sums to zero. Stripe's own image is water in pipes ending in reservoirs. At steady state the terminal (non-clearing) reservoirs, such as a business's balance, are full and the intermediate (clearing) pipes, such as charge_undisbursed, are empty. Water stuck in a pipe is an unresolved balance, which means a missing, late or wrong event. The query that finds every problem among billions of transactions is short: "find the clearing accounts with non-zero balance".
  • Timeliness. Did data arrive on time? Producers stamp each event when it first enters Stripe, and Ledger measures the delay until it lands in Ledger. A hard delivery window, with headroom left for downstream reporting, keeps 99.999% timeliness for deadline-driven work such as the monthly Accounting Close.
  • Completeness. Is anything missing entirely? Clearing cannot catch an event that never arrived and whose partner never arrived either. So Ledger adds explicit cross-system checks (every id in a producer database must have a matching Ledger event) and statistical arrival models per account type: if history says events of this type normally land by a certain time and they have not, that is treated as probable missing data.

Scores roll up per fund flow, per team and company-wide into one DQ score. A system at 99.99% is very unlikely to hide a major problem, which turns a distributed debugging problem into a tabulation exercise. The outcome numbers are worth memorising: 99.99% of dollar volume is fully ingested and verified within four days, 99.999% of activity is monitored, categorised and triaged by tooling, the long tail is handled manually, and overall more than 99.9999% of money movement is explainable, while data volume grew 10x.

Tooling and correction. The team-level view shows each metric, the dollar impact for leaders, auto-generated tickets and links. In one example a 50% score on Aging Balances meant some clearing issues had persisted. Clicking a point on a graph of an uncleared account (for example a processing fee that should have been invoiced and paid) generates Presto SQL that pulls reference keys, metadata and owners. If the root cause is an infrastructure or third-party incident, the item can be reassigned and excluded from alerting, and incident-attributed issues can later be analysed for cross-team impact. Ledger problems are rarely transcription bugs in Ledger itself; they usually expose real bugs in an integration, a producer or the physical money movement.

Because Ledger is immutable, a fix cannot be an UPDATE. Corrections revert and reprocess prior operations, often by republishing from the source system. Stripe built a migration utility for this, guarded by a DQ tool that produces an out-of-band report of the proposed change's production impact. Every correction goes through a two-phase review and commit of both the data and its DQ impact: in effect, CI for ad-hoc data repair.

Overlooked constraints.

  • Double-entry only proves internal consistency. If both legs of a wrong movement are recorded consistently (right amount, wrong business on both legs), clearing passes. That is why completeness checks against producer databases and, beyond Ledger, reconciliation against bank statements are still needed.
  • "Steady state" needs a clock. A charge in flight legitimately has a non-zero clearing balance. Every clearing account type therefore needs an expected clearing time; an alert means "non-zero for longer than expected", which is what the Aging Balances metric captures.
  • Immutability makes fixes slower. Corrections are new events with review, not edits. This is deliberate: you can always reproduce any past number by replaying events up to that point, which is what auditors need.
  • Wrong property values create ghost accounts. A release event tagged with business B instead of A does not fail; it silently creates two non-zero clearing accounts, one for A and one for B. The error shows up as a pair, which is a useful debugging hint.

What Stripe sacrificed. Latency and simplicity. Full verification takes up to four days for 99.99% of volume, because partners report on their own schedules; the stated next goal is minute-level timeliness for faster fraud and financial response. Every producer team must also model its system as a fund flow and publish events with correct identifiers, which is real integration work. In return, correctness becomes a number that can be measured, owned and improved.

Deep Dive: double-entry as a conservation law, and what the DQ numbers mean in dollarsShow

Conservation. Give every event a set of postings (account, amount) whose amounts sum to zero. Then the sum of all account balances is always zero, no matter how many events are applied or in what order, because addition is commutative. This is why out-of-order arrival is harmless: the balance of charge_undisbursed(biz A, id 123) is +creation − release whichever lands first. A temporary negative balance (release before creation) is just as diagnostic as a positive one once the expected clearing time has passed.

Why the clearing query scales. Balances are a commutative aggregate: balance(account) = Σ amounts. That can be computed incrementally per partition and merged, so "every clearing account with non-zero balance older than its SLA" is one group-by over a partitioned table, not a join across billions of rows. With 5 billion events/day and, say (handbook's own illustration), two postings each, that is 10 billion posting rows per day, about 116,000 rows per second on average. A columnar engine scanning roughly 50 bytes per posting reads about 500 GB per day of data, which is routine for Presto or Spark.

What 99.9999% explainability means. Using the public Black Friday to Cyber Monday figure of $18.6B, an unexplained fraction of 10⁻⁶ is about $18,600 over that weekend. At 99.99% (four nines) it would be $1.86M. The gap between four and six nines is the difference between a rounding error that analysts can chase by hand and a number that needs a team. That is why the platform splits work into tiers: automation clears the bulk, tooling triages the 99.999%, and humans handle the last part per million.

Detecting missing data statistically. Suppose an account type has historically received events at an average of λ = 2,000 per hour in a given hour of the week. If arrivals are roughly Poisson, the chance of seeing fewer than 1,800 in that hour is about the chance of a normal value more than (2,000 − 1,800)/√2,000 ≈ 4.5 standard deviations below the mean, which is around 3 in a million. So a 10% shortfall in a busy hour is almost certainly real missing data, while for a quiet account (λ = 20) the same 10% shortfall is about half a standard deviation and means nothing. Completeness alerts therefore need per-account-type baselines and volume-aware thresholds, which is what Stripe's per-account-type models provide. (The Poisson framing and numbers here are the handbook's illustration.)

A minimal posting rule in SQL. The invariant can be enforced at write time:

-- every journal entry must balance
SELECT entry_id
FROM ledger_postings
GROUP BY entry_id
HAVING SUM(amount_minor) <> 0;   -- must return zero rows
 
-- clearing accounts stuck past their expected clearing time
SELECT account_type, account_key, SUM(amount_minor) AS stuck
FROM ledger_postings p
JOIN clearing_sla s USING (account_type)
WHERE p.created_at < now() - s.max_age
GROUP BY account_type, account_key
HAVING SUM(amount_minor) <> 0;

Amounts are stored as integers in the currency's minor unit (cents, paise) to avoid floating-point drift. The general accounting background lives in Payment System.

Lesson 17: Reconciliation at scale, from nightly scripts to durable event-driven sync#

Assumptions. This three-part series (James Beswick, August 2025) is advice for Stripe users: keeping a product catalogue in your own database aligned with Products and Prices in Stripe. The key assumption is that scale changes the problem class. With hundreds of products, a person can eyeball a dashboard, a nightly SQL script can fix drift, and on-demand reconciliation is fine. With millions of products, manual checks are impossible, line-by-line comparison can take days, and the catalogue changes faster than a full comparison can finish, so a point-in-time "consistent" snapshot never exists.

The series frames this historically. In the mainframe era one database held everything and updates were atomic. In the client-server era data spread across several databases, but all inside your walls, so transactions and distributed locks were still available. In the cloud and SaaS era product data lives in your database, payment terms in Stripe, stock in a logistics provider and copy in a headless CMS. Each has its own model, rate limits and availability, and you control none of the others. Perfect synchronisation becomes an aspiration; the engineering target is bounded, detectable, repairable drift.

The two data models also differ on purpose. Stripe's product model is payment-focused: name, identifiers, short description for checkout and receipts, prices in multiple currencies, tiered, usage-based and recurring pricing, trial and grace periods and proration rules, plus limited metadata. Your internal model is merchandising and operations: category trees, inventory, rich descriptions, specs, media, cost and margin data (which must never leave your systems). Reconciliation therefore starts with a mapping decision: which attributes belong where, and how they transform.

Production architecture: two scenarios.

Scenario 1, one-way sync (your system is the source of truth). The naive version: a product change fires an event, a Lambda calls stripe.products.update, logs success, and moves on with no record. It fails in four ways. A Stripe outage loses the change because nothing retries. A bulk catalogue refresh triggers Lambda throttling, and throttled invocations drop changes. Bursts exceed the Stripe API rate limit, and without backoff the client keeps hammering. And there is no observability, so nobody knows which products drifted.

The robust version puts a durable queue (SQS or Kafka) between the change and the API call. A worker drains it at a configured rate below the quota, deletes a message only after a confirmed success, retries failures with exponential backoff, and moves persistent failures to a dead-letter queue for human review. In the post's batch handler, if any record in a batch fails the function throws, so SQS keeps the batch. Queue depth becomes the health metric for sync, and the rate can be raised during a big sale and lowered in maintenance windows.

Scenario 2, bidirectional sync (finance edits some attributes in Stripe, product teams edit others internally). The traditional answer is periodic ETL: extract snapshots of both sides, transform (map schemas, clean, normalise, aggregate), then a reconciliation engine diffs and loads fixes through a staging area. Its weaknesses: hours or days of known drift between runs, brittle transformation rules that break on every schema change, conflict rules (same field changed both sides, updated here but deleted there) that multiply, and cost that grows with volume. The event-driven answer streams Stripe changes through Event Destinations to an Amazon EventBridge partner event bus, buffers them in SQS, emits symmetric events from internal systems, and has dedicated sync services apply each change to the other side. Drift shrinks from hours to seconds or minutes, every change is an auditable event, and each change is resolved in isolation instead of in a giant batch diff.

Tools named in part 3, and where each fits.

NeedToolsFits when
Real-time streamingApache Kafka, Apache FlinkPrice or availability must stay tight; Flink when rules need history (stateful)
Capture DB changes without code editsDebezium (CDC)Retrofitting events onto an existing database
Declarative streaming ETL with quality checksDatabricks Delta Live TablesContinuous reconciliation with built-in expectations
Periodic deep reconciliationApache Spark, AWS Glue, Snowflake, dbtLarge diffs where hours of delay are fine; dbt for the mapping rules
ValidationGreat Expectations, Apache NiFi, TalendAsserting expectations about synced data
ConnectorsAirbytePulling Stripe data incrementally without custom code

The common production answer is both: streaming for freshness plus a periodic batch "deep reconciliation" that catches whatever the stream missed. See Change Data Capture and Batch and Stream Processing.

Best practices.

  • Directional source of truth. Not one master for everything, but one owner per attribute: the PIM or ERP owns names, descriptions, categories and relationships; Stripe owns billing cycles, trials and discount rules; the warehouse system owns stock. Write the ownership map down and draw it, so nobody "helpfully" edits a non-authoritative copy.
  • Idempotency everywhere. Use Stripe idempotency keys derived from the content of the operation, not random values, so a retry of the same change is recognised. Deduplicate in queue consumers by message id or natural key. Compare current and desired state before calling the API, which saves quota. Use content hashes rather than timestamps to decide whether anything really changed.
  • Explicit conflict rules. Newest timestamp wins (only if clocks are trustworthy, which is often forgotten); the more complete source wins for certain fields; critical fields like price and availability go to manual review with context; non-critical fields follow field-specific rules and fallbacks. Review the rules as the business changes.
  • Soft deletes and tombstones. Mark products inactive instead of deleting them, and keep a small tombstone (id, deleted-at, by whom) so reconciliation can tell "deliberately removed" from "lost by a sync bug". Purge only by a written policy; archive with progressively less detail.
  • Measure the sync. Track sync latency, conflict rate and resolution patterns, and audit periodically.

Overlooked constraints.

  • "Delete" is the hardest operation to sync. If a record is simply gone, the other side cannot distinguish deletion from never-synced. Tombstones turn absence into a positive fact.
  • Bidirectional sync can echo. A change applied from A to B emits a B change event that flows back to A. Without an origin marker or a content-hash check, the two sides ping-pong forever. The content-hash rule above is also the echo breaker.
  • Last-writer-wins needs comparable clocks. Two systems run by different organisations have independent clocks; a few seconds of skew can make an older edit win. Prefer version numbers from the owning system or per-field ownership over timestamps.
  • A throwing batch handler retries the successes too. In the post's pattern, one poison message makes the whole batch return to the queue, so already-applied updates run again. That is only safe because the updates are idempotent; partial-batch failure reporting (SQS supports reporting individual failed message ids) reduces the rework.

What is sacrificed. The durable, event-driven design costs more moving parts (queues, DLQs, two sync services, ownership docs) and gives up strict consistency for eventual consistency with a bounded lag. The batch design keeps simplicity and low cost but accepts known drift windows. Most real systems pay for both and let each cover the other's blind spot.

Deep Dive: sizing a catalogue sync against a rate limit, and finding drift efficientlyShow

Throughput budget. Assume (handbook's illustration) 2 million products, a sync worker allowed 50 writes per second to leave headroom under the account's rate limit, and a nightly bulk price change touching 400,000 products. Draining takes 400,000 / 50 = 8,000 s, about 2.2 hours. If the business needs new prices live within 30 minutes, the options are: raise the allocated rate to 400,000 / 1,800 ≈ 222 writes/s (which may exceed the limit), prioritise the queue so best-sellers sync first, or change the model so one Price object is reused and only a reference changes. The arithmetic decides the design before any code is written.

Why a full diff is expensive and how to avoid it. Comparing 2 million records one by one through an API at 100 reads/s takes 20,000 s, over 5.5 hours, and the catalogue changes during the scan. Better approaches:

  • Content hashes. Store hash(mapped_fields) on both sides (in Stripe, in metadata). Diffing hashes in a warehouse is a cheap join; only mismatches need API calls.
  • Merkle-style bucketing. Split ids into, say, 4,096 buckets by hash(id) mod 4096, compute a hash per bucket on each side, and descend only into buckets whose hashes differ. If 300 records drifted, at most 300 buckets differ, and you re-read about 300 × (2,000,000 / 4,096) ≈ 146,000 records instead of 2 million. This is the same anti-entropy idea Dynamo-style stores use (see Consistent Hashing for the partitioning side).
  • Incremental windows. Reconcile only records changed since the last watermark, plus a slow full sweep spread across the week.

Content-based idempotency key. A retry must produce the same key, so derive it from the intent:

import { createHash } from "crypto";
 
function syncKey(productId: string, fields: Record<string, unknown>): string {
  // canonical JSON: sorted keys so equal content gives equal bytes
  const canonical = JSON.stringify(fields, Object.keys(fields).sort());
  const digest = createHash("sha256").update(canonical).digest("hex");
  return `prod-sync:${productId}:${digest.slice(0, 32)}`;
}
// The same change retried gives the same key, so Stripe replays the first result.
// A genuinely new change to the same product gives a new key.

One caution: Stripe retains idempotency keys for a limited window (Stripe recognises a key for 24 hours, see Lesson 20), so a content key protects retries within a day, not a re-sync weeks later. The current-versus-desired state check covers that longer horizon.

Lesson 18: Stripe Credits, a logical balance built on real money infrastructure#

Assumptions. For years Stripe took every fee from the user's main payment balance and ran incentives as ad-hoc discounts or manual cash adjustments. That caused two problems. Product silos: discounts applied only to card processing, so they could not encourage users to try Atlas, Billing, Connect or Radar. Confusing accounting: users paid the full fee and later received a retroactive refund or discount, with no visible running balance. The 2026 post (Pratik Gupta and Sai Samant) describes the replacement, Stripe Fee Credits: a virtual, non-withdrawable balance that can only pay eligible Stripe fees and is kept separate from the payment balance. Stripe assumed credits must be just as auditable as real money, with dual approval and correct tax treatment, but must never become real money by accident.

Production architecture: three layers.

  1. Credits engine. A standalone gRPC service that is the system of record for credit metadata, policy, lifecycle and audit history. The Credit object encodes the policy, its economic purpose (prepaid or incentive), and which entities may use it, so one credit can be shared across several user accounts. The lifecycle is a finite-state machine, and every transition goes into a papertrail with dual approval. Each change records an actor, a timestamp and an approval link. Compliance never had to ask for logging, because it existed from the first commit.
  2. Logical financial accounts. The key insight was regulatory. Credits are not user funds: a prepaid credit is money Stripe has already received, and an incentive is a cost Stripe absorbs. Both are corporate funds, so they need no safeguarding, no sweep to a bank account and no reconciliation against a cash position. Rather than build a new balance system, Stripe extended its Money Movement and Storage (MMS) platform. In MMS a financial account can hold a balance and take part in transfers, and every existing one (merchant balances, settlement accounts, treasury accounts) is backed by a real bank account. Stripe added a variant that is purely logical: it carries a ledger balance that never corresponds to cash.
  3. Fee settlement orchestration. Instead of discounting after the fact, the fee settlement engine applies credits just in time. When a fee is assessed, it checks eligibility, chooses credits so as to minimise waste (for example, using credits that expire soonest), and debits the logical credit account before the fee ever touches the primary balance.

Guardrails against logical-to-real leakage. The worst possible failure is a logical ledger entry triggering a real cash movement. Two guardrails prevent it.

  • Movement restriction. All value moves through an Originated Money Transfer (OMT), an existing MMS workflow with a three-phase ledger lifecycle: submitted → prepared → disbursed. MMS now rejects, at platform level, any OMT between a logical account and a real one. Logical accounts can only transfer to other logical accounts.
  • Cash sweep isolation. MMS runs automatic intercompany sweeps from ledger data. If logical accounts were counted, a $100 incentive credit could cause a $100 real-cash sweep between Stripe entities, moving money that does not exist. Logical-account entries are excluded from sweep calculations, agreed with the cash-management team.

Two funds flows with the same user experience. Users see one thing: credits apply automatically and the Dashboard shows a running balance. Underneath there are two completely different ledgers.

  • User-funded (prepaid). Suppose a merchant signs a $1,000 prepayment. The invoice creates $1,000 of uncollected deferred revenue. When it is sent, the ledger records Stripe's obligation to deliver future services and the merchant's outstanding payment. When the merchant pays, the credits engine fires an inbound OMT that funds the merchant's credit account with $1,000, and real cash lands in a real Stripe account as deferred revenue. Later a $10 fee plus $1 tax is assessed. The $10 is paid from credits through an outbound OMT carrying the right product identifier, so revenue is attributed to the product used, and $10 moves from deferred revenue to revenue. The $1 tax is collected from the merchant's payment balance through the normal fee path. If credits expire unused, the remainder becomes breakage revenue with its own tax treatment. This was the first flow at Stripe that let merchants prepay fees annually.
  • Stripe-funded (incentive or courtesy credit). Now the most used type. No cash moves. An inbound OMT goes from a cashless corporate account to the merchant's credit account. When fees are assessed, an outbound OMT moves value from the credit account back to the corporate account, and a tax write-off event moves the tax from the uncollected-taxes ledger account to a write-off account, because the credit is effectively a discount and neither party pays that tax.
  • Effective time. The accrual event uses the fee record's creation date, not the later invoice date, so revenue lands in the right accounting period when an invoice crosses a month boundary.

Merging the two flows into one would have been an audit nightmare, because their tax treatments are incompatible. Stripe kept two flows, each with its own accounts, events and sign-off, and judged the duplication worth it. The same primitive now powers sales-contract incentives, prepaid annual deals, startup acquisition credits, Atlas onboarding credits and courtesy credits, in 26+ countries, without bespoke engineering per programme. Next on the roadmap: near-real-time settlement on credits and multi-settlement (paying one fee from several sources).

Overlooked constraints.

  • The hard part is integration, not the balance. Tracking a number is easy. Keeping it inside accounting, tax, reporting and the data warehouse without special cases, and without ever leaking into cash, is the real work. Reusing MMS events meant the financial data warehouse got the same fields as any other funds flow.
  • Regulatory classification drives architecture. Deciding that credits are corporate funds, not user funds, removed safeguarding and reconciliation entirely. Classify the money before you design the system.
  • A shared primitive needs negative capabilities. A logical account is "a financial account that cannot do certain things". Those prohibitions must be enforced by the platform (OMT checks, sweep exclusions), not by convention in each caller.
  • Time semantics matter for revenue. Event time (fee created) and processing time (invoice issued) differ, and accounting periods depend on the first.

What Stripe sacrificed. Some simplicity and code reuse: two funds flows instead of one, cross-team sign-off before the first dollar moved, and dependency on the MMS team for platform-level checks. In exchange, credits inherit years of battle-tested auditability and need no parallel reporting pipeline.

Deep Dive: the prepaid credit as journal entries, and choosing which credits to burnShow

Journal entries for the $1,000 prepaid example. Using the double-entry rule from Lesson 16 (each entry sums to zero; debits positive, credits negative), a simplified version (handbook's illustration of the flow the post describes) is:

StepDebitCreditAmount
Invoice sentAccounts receivable (merchant)Deferred revenue (obligation)$1,000
Merchant paysCash (real Stripe account)Accounts receivable$1,000
Credit funded (logical)Merchant credit accountCredit funding clearing$1,000
Fee $10 drawn from creditCredit funding clearingMerchant credit account$10
Revenue recognisedDeferred revenueRevenue (product X)$10
Tax $1 from payment balanceMerchant payment balanceTax payable$1
Credits expire with $200 leftDeferred revenueBreakage revenue$200

The real cash entry happens once, when the merchant pays. Everything about drawdown moves only between logical or accounting accounts, which is exactly what the movement restriction guarantees.

Which credits to burn first. A merchant may hold several credits with different expiries and eligibility. "Minimise wasted credits" is a small scheduling problem. If every credit can pay every fee, earliest expiry first is optimal: any plan that burns a later-expiring credit while an earlier one is still usable can swap them without making anything worse, and the swap never increases waste (the classic exchange argument). When eligibility differs (credit A pays only Billing fees, credit B pays any fee), greedy can fail: spending B on a Billing fee that A could have paid leaves a later Radar fee unpaid. The general case is a bipartite matching or flow problem between fees and credits; in practice a rule of "most restrictive eligible credit first, then earliest expiry" handles most cases.

Idempotency of drawdown. Fee settlement retries must not burn a credit twice. Keying each drawdown OMT by (fee_id, credit_id) with a unique constraint makes the retry a no-op, the same pattern as API idempotency keys in Lesson 1, applied inside the ledger.

Lesson 19: Thin events and event notification handlers#

Assumptions. Handling events is central to any Stripe integration, and the 2026 post (David Brownman, tech lead of the Developer SDKs team) names two pains. Authoring: there are many event shapes and keys, and outside TypeScript the static types give little guidance, so typos in event-type strings only show up at runtime. Maintenance: classic ("snapshot") event payloads are rendered in a specific API version (Lesson 3), so upgrading the event destination or a strongly typed SDK can change the payload shape and break the handler in production.

Production architecture. Thin events solve maintenance. They are unversioned JSON payloads that carry the event type, a reference to the related object (for example related_object.id) and the account context, but not a full rendered object. Because the payload is identical across API versions, any SDK version can parse it, which makes upgrades safe. To get details you call fetchEvent() or retrieve the related object, and the response is rendered in your SDK's version.

Event notification handlers solve authoring. Before them, a webhook endpoint had to verify the Stripe-Signature header, parse the notification, switch on type strings, and pass the Stripe-Context header by hand on every follow-up call for a connected account (forgetting it queries the wrong account). Business logic ended up tangled with plumbing. With a handler you create stripe.notificationHandler(webhookSecret, fallback) with a fallback callback for unhandled types (it reports whether the SDK knows the type at all), then register handler.on("v1.billing.meter.no_meter_found", fn). The SDK verifies the signature, routes by type, casts to the right type, and passes a StripeClient pre-bound to the event's context, so follow-up calls automatically target the right account. In TypeScript, handler.on checks the callback's argument types at compile time. Callbacks are plain functions, so they can be unit-tested. The pattern ships in all seven server-side SDKs (Node, Python, Java, Go, Ruby, PHP, .NET), each in its own idiom, generated from the same pipeline that Lesson 4 describes. Future work includes checking that a handler listens for every event type the endpoint is subscribed to.

Overlooked constraints.

  • Thin is a trade, not a free win. Every event now needs at least one API read to be useful, which counts against the rate limit (Lesson 5) and adds a network hop of latency. Lesson 7's fetch-before-process pattern becomes mandatory.
  • Fetching gives current state, not event-time state. If an object changed twice quickly, two thin events both fetch the latest state. That is usually what you want (no stale snapshots, no out-of-order overwrites), but if you need the exact state at event time, the snapshot is gone.
  • Return 200 fast. The sample handler processes inline before answering. Under load, heavy callbacks should hand work to a queue (Lessons 7 and 20) so Stripe's delivery does not time out and retry.
  • Unknown types must not crash. Stripe can add new event types at any time. The fallback callback makes "unknown type" an explicit, logged case rather than an exception that returns 400 and triggers redelivery.

What Stripe sacrificed. Payload self-sufficiency and some API capacity: every consumer pays a fetch per event. In return, events never break on upgrade and the SDK can guarantee types. The general lesson: separate the notification ("something changed") from the data ("what it is now"), and version only the data.

Deep Dive: thin versus fat events, by the numbersShow
PropertyFat (snapshot) eventThin event plus fetch
Payload sizeFull object, often several KBType, ids, context, typically under 1 KB
Tied to API versionYes, rendered per versionNo, unversioned
Reads per event0At least 1
Ordering riskOlder snapshot can overwrite newerFetch returns latest, ordering mostly harmless
Data exposure in transitWhole objectIds only
Replay after a long outageReplays stale snapshotsReplays fetch current state

Rate-limit cost. Suppose (handbook's illustration) a platform receives a burst of 30,000 events in 10 minutes during a billing run, i.e. 50 events/s. With thin events that is 50 extra reads per second on top of normal traffic. If the account's read budget is 100 requests/s, half of it now goes to event fetches. Two mitigations apply. First, coalesce: if 5 events for the same subscription arrive within a second, fetch once. With a 1-second coalescing window, a burst where each object averages 3 events cuts fetches by roughly two-thirds. Second, queue and throttle the fetches as in Lesson 7, so the burst drains at a fixed rate instead of spiking.

Why "fetch current state" is ordering-safe. If handlers apply snapshots, two deliveries that arrive out of order (v2 then v1) leave the stale v1 in your database. If handlers only use events as triggers and always fetch, both deliveries read v2 (or later), so the final state converges no matter the arrival order. This turns an ordering problem into an at-least-once delivery problem, and at-least-once with idempotent apply is easy. The general theory is in Delivery Semantics.

Lesson 20: Because nobody likes being charged twice#

Assumptions. A customer taps "Pay", their connection drops, they refresh and tap again, while your backend is also retrying the first request after a timeout. Without protection that is two charges, followed by refund requests, support tickets and lost trust. The post (Ben Smith, 2025) assumes failure is normal: timeouts, crashes, database locks, downstream errors and users closing tabs mid-payment all leave a payment in an uncertain state. The fix combines two tools, each covering the other's gap.

Production architecture.

  • Idempotency keys prevent duplicates at the provider. Generate a unique key (for example a UUID) for the action, send it in the Idempotency-Key header, and Stripe stores it and returns the original response to any repeat with the same key. Stripe recognises a key for 24 hours.
  • Message queues make sure the attempt actually happens. The "Pay" request is enqueued (RabbitMQ, SQS, Kafka). A worker pool consumes it, calls Stripe with the key and confirms the PaymentIntent. On success the message is deleted. On failure it returns to the queue and is retried after a delay. After the maximum attempts it goes to a dead-letter queue for inspection. With SQS and Lambda, if the function times out or errors, the message reappears after the visibility timeout, which gives the retry for free.

Idempotency without a queue means a dropped request is never retried. A queue without idempotency means every retry can charge again. Together: the queue guarantees a retry, and idempotency guarantees the retry is safe. The post's (fictional) example is a developer-tools company selling conference swag during a keynote: flaky mobile connections, a backend that generates the UUID and enqueues the job, a Lambda worker that confirms the PaymentIntent, and only ever one PaymentIntent however many times the worker retries.

Common pitfalls the post lists, with the reason each breaks.

  1. Reusing a key across operations or users. A key should name one action ("create payment for order 123"), not a session. Sharing it can return another user's payment response.
  2. Generating the key too early (at app start or page load). If the user changes the cart, the stale key binds the new request to the old response. Generate it just before enqueueing or calling Stripe.
  3. Retrying without the original key, which happens when infrastructure (a queue worker, a load balancer) retries and builds a fresh request. That retry is a brand-new charge. Store the key in the message.
  4. Idempotency without a queue. If Stripe is briefly down and nothing retries, the payment is simply lost.

Overlooked constraints.

  • The 24-hour window bounds the retry horizon. A job stuck in a DLQ for two days and then replayed with the same key may be treated as new. DLQ replays must first check whether the order is already paid (look up the PaymentIntent by your order id stored in metadata).
  • The customer's double-click is a different request. Two taps produce two backend requests. If each generates its own UUID, the queue plus idempotency does not help. The key must be derived from something stable, such as the order id or a checkout-session id created once on the server, so both taps map to one key.
  • Visibility timeout must exceed the worst-case call time. If the timeout is shorter than a slow Stripe call, the message reappears while the first worker is still running and two workers call Stripe concurrently. The key still protects you (Stripe returns a conflict or the same result), but you waste capacity and logs get confusing.
  • Asynchronous payment changes the UX. With a queue, the "Pay" click returns "processing", not "paid". The UI must poll or listen (via webhooks or Real-time Communication) for the final result.

What is sacrificed. Immediate feedback and simplicity: the payment becomes asynchronous, and you now operate a queue, workers and a DLQ. In return a transient failure becomes a delay instead of a duplicate charge or a lost sale.

Deep Dive: how many duplicates would you see without keys?Show

Assume (handbook's illustration) 1 million payments per day, a client timeout of 10 s, and 0.3% of requests timing out after Stripe already charged (the request succeeded but the response was lost). Without idempotency keys, an automatic retry on every timeout gives 1,000,000 × 0.003 = 3,000 duplicate charges per day. If the average order is $40, that is $120,000 a day of erroneous charges to refund, plus support cost and dispute risk. With keys, those 3,000 retries return the original response and the duplicate count becomes 0, for the cost of one stored key per request (a few hundred bytes, about 300 MB per day at this volume, deleted after 24 hours).

Choosing max receives before the DLQ. With exponential backoff starting at 30 s and doubling, attempts happen at about 0, 30 s, 1.5 min, 3.5 min, 7.5 min and 15.5 min. Five retries cover a 15-minute provider blip, which is longer than most real outages of a single dependency. Raising the limit to 8 extends cover to about 2 hours. The constraint is the 24-hour key window: keep the total retry horizon well under 24 hours, so every automatic retry is still protected. Anything older goes to a human who checks payment status first.

Key derivation. A stable key from a server-side checkout id beats a random UUID per request:

// created once, when the server creates the checkout session
const checkoutId = await db.createCheckout(orderId, amountMinor, currency);
const idempotencyKey = `pay:${checkoutId}`;   // same for every retry and every tap
await queue.send({ checkoutId, idempotencyKey });

If the cart changes, a new checkout (and therefore a new key) is created, which avoids the stale-key pitfall. More background: Idempotency.

Lesson 21: The Global Money Management Platform#

Assumptions. Global money movement is fragmented. There is a patchwork of payment rails (the networks that move money electronically) with incompatible message standards, different settlement windows and operating hours. Liquidity must be managed across countries and currencies. Transfers fail. FX costs money and adds risk. Some countries, and some US states, impose safeguarding and licensing rules that restrict where money may go or require corporate cash to be held while a movement is executing. The 2026 post (Rishabh Jain, David Hatanian, Sai Samant) describes the move away from an early design in which each product was a vertical stack with its own rail integrations and its own balance built on a shared Books database. That design let teams move fast and own their domain at first.

The complexity tax. Stripe Issuing, to let users add funds to cards, had to track a balance, understand how incoming payments progress and settle, reconcile its records with money that actually arrived, and manage the risk of users spending unsettled funds. Topups and Treasury each supported ACH debits in their own way. Every new market meant redoing rail and regulatory work per product, and capabilities rarely transferred. Around 2021, while planning what became Global Payouts, Stripe decided that another vertical stack would slow global expansion, and it chose to build shared programmable economic infrastructure.

Production architecture. The Global Payments and Treasury Network (GPTN) is the internal platform. Its core is the Global Money Management Platform, shared by every product that stores money ("money at rest") or moves it ("money in motion"): Payments, Connect, Embedded Finance, Issuing and Capital. It provides primitives for ledgering, fund-state modelling, rail lifecycles, reconciliation, controls, compliance and liquidity. It also comes with explicit guarantees: consistent meanings for terms like "available balance" and "posted" across countries, currencies and rails; fault tolerance through retries, idempotency, fallbacks and reconciliation; risk controls and accounting invariants built in; and user promises (settlement times, transfer delays) limited to what the platform can actually enforce. Since late 2025 the product layer above it is much thinner.

Three abstractions contain the complexity.

  1. Logical versus physical money movement. Logical movement is what users see: funds owed, a balance going pending then available, a payout arriving on the promised date. Physical movement is cash moving between banks, partner rails and Stripe entities to back those promises. Decoupling them lets Stripe keep promises steady while the physical side has delays, cutoffs and outages. The example: a rail settles in two business days 99.9% of the time and occasionally in three. Stripe still promises two days and holds liquidity buffers to cover the shortfall. The product team never learns that the delay happened. In extreme crises, controls can pause activity and cap how far logical and physical money diverge. Product teams build against the stable logical layer, while new rails, banks and regions change underneath.
  2. GPTNAccount (money at rest). One logical account abstraction replaces per-product balances, because the states money passes through (settling, available, revoked) turned out to be product-agnostic. Each account has strict boundaries: one legal entity, one jurisdiction, one currency, one regulatory treatment (payment funds may be governed differently from stored value). When Stripe can hold a new currency in a jurisdiction, it provisions the account type and every product can use it immediately. Features like deposit insurance (for example FDIC in the US) or regional safeguards are added once at the platform layer. Payments financial accounts (private preview, 2026) combine payments and treasury balances in one account on top of GPTNAccounts. Rebasing Treasury on the platform also removed the forced currency conversion that multi-currency users previously had to do before moving funds into Treasury.
  3. GPTNWorkflows (money in motion). Money movement has long lifecycles: ACH returns and revocations after funds seem deposited, card refunds and disputes long after capture, banks and networks going offline. GPTNWorkflows give products a rail-agnostic contract: explicit states (initiated → pending → settled → finalized), idempotent execution, explicit reversals, returns and disputes, reconciliation against external events, and consistent ledgering and availability semantics. The Transfer workflow is used by dozens of products, which can integrate within hours and launch within days. Adding a new cross-border "cash corridor" gives every product that uses the workflow the new route at once.

The launch-time evidence. The first US version of financial accounts and Treasury took nearly a year, and the UK took nearly another year. That was because the first build carried hidden region-specific assumptions (particular bank accounts, currencies, settlement times) that only surfaced when a second region pushed on the abstraction. After those were fixed, the EU took about three months and Australia six weeks, with most of that time spent on genuinely local needs such as a distinct regulatory report.

Overlooked constraints.

  • An abstraction is not proven until the second user. The UK launch exposed what the US build assumed. Plan for the second region (or second product) to cost almost as much as the first, and only the third onwards to be cheap.
  • Promises need buffers, and buffers cost capital. Promising two days when settlement sometimes takes three means pre-funding the gap from Stripe's own liquidity. The size of the buffer is a direct function of the tail of the settlement-time distribution.
  • "Settled" is not "final". ACH returns and card disputes can reverse money long after it looked done, which is why the workflow separates Settled from Finalized.
  • Account boundaries are regulatory, not technical. Mixing currencies or legal entities in one account would be simpler to code but would break safeguarding and reporting rules.

What Stripe sacrificed. Team autonomy and early speed. Vertical stacks let each product ship alone. A central platform means product teams depend on platform teams, platform changes need care because dozens of products use them, and the first two regional launches were slower than a bespoke build might have been. The payoff is that each later expansion is cheaper.

Deep Dive: sizing a liquidity buffer for a settlement promiseShow

Suppose (handbook's illustration) a rail delivers $50M per business day to Stripe in some market, settling on day 2 with probability 99.9% and on day 3 with probability 0.1%. Stripe promises day-2 availability to users. On a normal day the expected late amount is 0.1% × $50M = $50,000, which a small buffer covers easily.

The danger is correlation. Late settlement is rarely independent per payment: a bank's batch fails, a holiday shifts a cutoff, a file arrives late. Then an entire day's $50M is late together. If such a full-day slip happens about once a year, the buffer needed to keep the promise that day is the whole $50M, not $50,000. That is a 1,000-fold difference from the independent-payments estimate. This is why Stripe also describes crisis controls that pause activity and limit logical-physical divergence: a buffer sized for the worst correlated event would tie up too much capital, so the platform keeps a buffer for common slips and a circuit breaker for rare ones.

Cost of the buffer. At a 5% annual cost of capital, holding $50M idle costs about $2.5M a year, roughly $6,850 a day. Holding $5M (enough for a 10% partial slip) costs $250,000 a year. The platform's choices (buffer size, corridors to pre-fund, when to trip controls) are capital-allocation decisions as much as engineering ones.

The lifecycle as a state machine. Modelling Settled and Finalized separately matters for availability rules. A conservative product makes funds available only at Finalized. A user-friendly product makes them available at Settled and carries the return risk, usually with a reserve sized from historical return rates (for ACH, returns are typically reported within a couple of business days, with some types allowed much later). Putting this choice into one workflow means one risk model is reviewed once, instead of every product team inventing its own. Related payment-system design: Payment Network.

Lesson 22: Radar, fraud detection in under 100 milliseconds#

Assumptions. Radar decides in the instant between a customer clicking "purchase" and the confirmation. The 2023 post (Ryan Drapeau) sets the constraints. Radar assesses more than 1,000 characteristics of a transaction and decides in under 100 ms. Fraud is rare, about 1 in 1,000 payments. Of billions of legitimate payments, Radar wrongly blocks only 0.1%. The tool must be accurate, fast and cheap per transaction, and it must balance blocking fraud against false positives (good payments blocked), which cost users revenue and annoy customers. Radar's biggest asset is the breadth of the Stripe network: a card or device seen at one business informs decisions at every other. Radar can let a payment through, block it, or divert it to extra checks such as 3D Secure.

Production architecture: three lessons from seven years.

Lesson A: don't get comfortable with your model architecture. Radar went from logistic regression to deep neural networks, and each architectural jump brought a comparable leap in performance. In mid-2022 it moved from an ensemble "Wide & Deep" model to a DNN-only model. The wide-and-deep idea comes from Cheng et al., "Wide & Deep Learning for Recommender Systems" (Google, 2016): a "wide" part memorises specific feature combinations and a "deep" part generalises. In Radar the wide part was XGBoost (gradient-boosted trees, Chen and Guestrin, "XGBoost: A Scalable Tree Boosting System", 2016). It worked, but XGBoost was hard to combine at scale with transfer learning, embeddings and long training runs, and it parallelises poorly, so retraining was slow and the many engineers working on the model each day could run fewer experiments.

Simply dropping XGBoost would have cost 1.5% recall, which was unacceptable. Making the DNN bigger raises capacity to learn both abstract features ("payment velocity", "unusual volume on a card") and fine-grained feature correlations, but too much depth overfits and memorises noise. The answer was a multi-branch architecture inspired by ResNeXt (Xie, Girshick, Dollár, Tu and He, "Aggregated Residual Transformations for Deep Neural Networks", 2017). ResNeXt's "network-in-neuron" idea splits a layer into many parallel small branches and sums their outputs. The number of branches ("cardinality") is a new dimension of capacity that improves accuracy more efficiently than adding depth or width. The result: training time fell by more than 85%, to under two hours, so experiments that used to run overnight could run several times a day. The next steps were transfer learning, embeddings and multi-task learning.

Lesson B: never stop looking for features. Feature engineering is the biggest lever. The team writes detailed investigation reports on past attacks, looks for signals such as a recurring pattern of throwaway emails used to create many accounts, searches the network for correlated timing, and meets weekly to discuss new fraud trends, including research into dark-web activity. Ideas become a prioritised list, each is implemented quickly and tested for model impact. Not all work. A Boolean "this business is under a distributed fraud attack" feature added little, because the model had already learned those patterns. Data volume is the other lever: unlike XGBoost, the DNN keeps improving as training data grows. With the faster training, a 10x increase in training transactions still gave significant gains, and a 100x experiment was under way.

Lesson C: explanation matters as much as detection. DNNs are harder to explain than simpler models, a cost Stripe accepted. Risk insights (2020) shows users which features pushed a decision, for example whether the cardholder name matches the email, or how many cards have been used from one IP address. Many cards from one IP can mean card testing, or a legitimate shared network, which is why the model weighs each feature in context. Later additions show maps of purchase and shipping locations and use Elasticsearch to retrieve related transactions quickly. Internally, a table lists the features that raised or lowered a specific score most, used to debug support cases. Users then improve the data they send or write custom allow and block rules. Over the same period, fraud shifted from mainly stolen cards to a mix that includes high-velocity card-testing attacks.

Overlooked constraints.

  • Labels arrive late. A fraud label usually comes from a chargeback weeks after the payment. Training data always lags, and recent attacks are under-labelled. This is why fast retraining and manual attack investigation both matter.
  • Blocked payments have no label. If Radar blocks a payment, you never learn whether it was really fraud. Training only on allowed payments biases the model. A common remedy is to let a tiny random sample of would-be-blocked payments through, or to score in shadow, to estimate the true rate (a general industry technique, not stated in the post).
  • The latency budget is shared. 100 ms must include feature fetches across the network's history, not just model inference. Features must be precomputed and served from fast stores, which is what Lesson 24 (Shepherd and Chronon) is about.
  • Recall and false positives pull in opposite directions. At a 1-in-1,000 base rate, even a small false-positive rate means many good customers blocked per fraud caught.

What Stripe sacrificed. Explainability and the simplicity of tree models. Stripe accepted a harder-to-explain DNN for faster training, better scaling and access to modern techniques, and then invested separately in explanation tooling to win back users' trust.

Deep Dive: base rates, precision and why 0.1% false positives is hardShow

Take 1,000,000 payments with a fraud rate of 1 in 1,000, so 1,000 fraudulent and 999,000 legitimate. Radar's stated false-positive rate is 0.1% of legitimate payments, so about 999 good payments blocked. Suppose (handbook's illustration) recall is 80%, so 800 frauds caught.

  • Precision = 800 / (800 + 999) ≈ 44%. Fewer than half of blocked payments are fraud, even though the model is excellent by any normal standard.
  • Halving the false-positive rate to 0.05% (500 blocked good payments) raises precision to 800 / 1,300 ≈ 62%.
  • Raising recall from 80% to 81.5% (the 1.5 points that dropping XGBoost would have cost) catches 15 more frauds per million payments. At an average fraud cost of $100 plus chargeback fees, that is about $1,500+ per million payments, which at Stripe's volume adds up to a very large sum. That explains why a 1.5% recall drop was unacceptable.

This base-rate effect is why fraud systems use three outcomes, not two: low-risk payments pass, high-risk payments are blocked, and the uncertain middle gets a challenge (3D Secure), which costs a little friction instead of a lost sale.

Why ResNeXt-style branches help. A layer with C branches, each a small transformation of width d, has roughly C × d² parameters if each branch is a d × d map, compared with (C·d)² for one wide layer of the same total width. With C = 32 and d = 4, that is 512 parameters versus 16,384: about the same "width" of features for 1/32 of the parameters. Fewer parameters for the same representational breadth means less overfitting and faster training, which matches the observed 85% training-time cut combined with no loss of memorisation. (Parameter arithmetic is the handbook's illustration of the general ResNeXt argument.)

Training-data scale. If training time is linear in data size and one run takes 2 hours, a 10x data run takes about 20 hours and a 100x run about 200 hours on the same hardware. That is why the switch to a parallelisable DNN came before the data-scaling experiments: the speed-up made 10x feasible and 100x a distributed-training problem rather than an impossible one. Related platform topics: ML System Design and Feature Stores.

Lesson 23: Railyard, training thousands of models on Kubernetes#

Assumptions. By 2019 (Rob Story's post) Stripe's ML scored hundreds of millions of predictions across many models built from billions of data points, with hundreds of new models trained each day. Models power Radar and Billing's retries of failed charges. Before Railyard, an engineer would SSH into a shared EC2 instance and start a Python process by hand. Open questions: how to go from ad-hoc runs to hundreds of automatic runs a day, how to support many frameworks with one interface, what metadata to track, where jobs run, and how to give each job the CPU, GPU or memory it needs. The assumption was that ML teams should focus on modelling, not operating infrastructure, mirroring how Stripe treats its own users.

Production architecture. Railyard is a Scala service with a JSON API that manages job history, state and provenance in Postgres. It launches each training run as a Kubernetes job, on a cluster that is run entirely by Stripe's Orchestration team. Training code is Python, packaged with Google's Subpar into one .par executable containing all dependencies (built with Bazel), placed in a Docker image with extras like the CUDA runtime, pushed to AWS Elastic Container Registry, and run with a simple python /railyard_train.par. A run fetches training and holdout data, trains, serialises the model and evaluation data to S3, streams logs to S3, and records results in Postgres. The outputs are a model identifier ready for production and evaluation data in S3.

API design: no DSL. Two extremes were considered. One was a custom DSL encoding scikit-learn pipeline components in the API so users write no Python. The other was users writing Python classes with defined inputs and outputs. Any DSL either tied Railyard to one framework or required constant updates as libraries changed. The chosen split: the API carries data sources, filters, feature names, label, holdout sampling and training parameters, while the training logic lives entirely in Python. A free-form custom_params JSON field holds hyperparameters, because nobody can predict every parameter a modeller needs. A request names the model, owner team, project and trainer; lists Parquet columns on S3; filters by date range, amount and country; holds out a date range (for example the last quarter) as test data; and names the Python workflow class.

The Python workflow contract. Every workflow extends StripeMLWorkflow: "we pass data in, you pass a trained model out, and we score and serialise it". The interface has hooks like fetch_data, preprocess, train and write_evaluation_data, with standard containers (Pandas DataFrame, Torch Dataset) but freedom in how they are produced. Some deep learning models stream batches with custom fetch code. Support grew from scikit-learn to XGBoost, PyTorch and FastText, and teams used it for things the designers never planned: time-series forecasting and word2vec-style embeddings.

Scheduling. Version one forked a subprocess per job from the Scala service using Java's ProcessBuilder and built a virtualenv each time, which was fine for iterating on the API but did not scale. Kubernetes provided what was needed: quick scaling by instance type, routing jobs to the right hardware, and queueing. A top-level compute_resource field (CPU, GPU, or memory-optimised) becomes a Kubernetes affinity (which nodes the pod should run on) plus a toleration (permission to run on nodes tainted, i.e. reserved, for that workload). CPU and memory limits are set from each job's historical and expected usage. High-memory and GPU jobs get a whole node each, and queue if none are free; light jobs share nodes. Large models can need hundreds of GB of memory.

Results and lessons. About 100,000 models trained in a year and a half. Radar's fraud model is built from hundreds of distinct models, trained and deployed daily by a dedicated service; other models retrain through Airflow tasks calling the Railyard API. When jobs outgrew CPU-optimised instances, they moved to memory-optimised ones the next day; when a backlog appeared, the cluster was expanded with one command. Takeaways from the post:

  • A generic, framework-agnostic API got used in unexpected ways.
  • A fully managed cluster run by another team is a force multiplier; operating it themselves would have needed more engineers and more time.
  • Central tracking of state and ownership changed support from "did you save the output anywhere?" to "what's your job id?".
  • Per-step metrics (data loading, training, serialisation, evaluation persistence) by team, project and machine moved the team from reactive ("my model didn't train") to proactive ("your model didn't train, here's why").
  • Memory-hungry jobs are still hard. Flexible Python lets modellers write workflows that run out of memory and get killed. Ideas: retry automatically on bigger instances, or move to distributed libraries like dask-ml.
  • Subpar works well with Bazel; starting again they might evaluate Facebook's XARs.

Overlooked constraints.

  • Reproducibility needs provenance. Retraining "the same model" weeks later only works if data paths, filters, code version and parameters are all recorded. Postgres provenance plus immutable images make that possible.
  • Holdout by date, not at random. Fraud data is time-dependent. The example request holds out a final date range, which tests the model on the future relative to training. A random split would leak future patterns into training and overstate accuracy.
  • Whole-node scheduling wastes capacity when a GPU job uses half a GPU node, but it prevents noisy-neighbour failures. Stripe chose predictability.

What Stripe sacrificed. API expressiveness (no DSL, no deep validation of custom_params) and some cluster efficiency (whole nodes for heavy jobs). In return they got flexibility that survived several ML framework generations and almost no infrastructure work for modelling teams.

Deep Dive: sizing a training cluster and the cost of whole-node schedulingShow

Assume (handbook's illustration) 400 training jobs per day: 300 light CPU jobs averaging 20 minutes on 4 cores, 80 high-memory jobs averaging 90 minutes on a whole 768 GB node, and 20 GPU jobs averaging 3 hours on a whole 8-GPU node.

  • Light jobs: 300 × 20 min × 4 cores = 24,000 core-minutes = 400 core-hours per day. On 96-core nodes that is about 4.2 node-hours, which is less than one node running all day.
  • High-memory jobs: 80 × 1.5 h = 120 node-hours per day, so at least 5 nodes busy around the clock, more if the jobs bunch together.
  • GPU jobs: 20 × 3 h = 60 GPU-node-hours per day, so at least 2.5 GPU nodes.

The GPU and memory pools dominate cost, which is why whole-node scheduling matters. If half the high-memory jobs only use 300 GB, packing two per node would save about 40 node-hours a day, but one job's memory spike could then kill its neighbour. Railyard's choice is the safe one, and its cost is visible in this arithmetic.

Queueing when everything starts at once. If Airflow triggers all 80 high-memory jobs at 02:00 and there are 10 nodes, they run in 8 waves of 90 minutes, finishing at 14:00. Raising the pool to 20 nodes finishes at 08:00. Staggering triggers, or adding more nodes during the nightly window and removing them afterwards, is a scheduling decision as much as a hardware one. Little's law applies: average jobs in the system = arrival rate × average time in system. Long queues mean too few nodes for the burst, even if average utilisation looks fine. The general background is in ML System Design and Feature Stores and Batch and Stream Processing.

Lesson 24: Shepherd, adapting Airbnb's Chronon for Stripe-scale features#

Assumptions. A feature is an input to a model, for example "total charges processed by this business over the last 7 days". Features must be found among hundreds of terabytes of raw data, go through several rounds of idea, prototype and evaluation, and then be served in production. Fraud is adversarial, so the time from idea to production matters. The 2024 post (Ben Mears) names two serving requirements that pull against each other:

  • Latency: time to fetch features at inference. Radar runs inside the payment path (Lesson 22), so feature latency adds directly to API latency.
  • Freshness: time until a new event changes the feature value. If one business suddenly spikes, its features must update quickly so models can react, including at other businesses.

More precomputation on write improves latency but costs freshness; more computation at serving time improves freshness but costs latency. Stripe needed both at billions of transactions.

Production architecture. In 2022 Stripe accepted Airbnb's invitation to be an early external adopter of Chronon, before Airbnb open-sourced it. Chronon met the requirements: a Python and SQL API, efficient windowed aggregations, both online and offline computation from one definition, and built-in online/offline consistency monitoring. But it had to be adapted to Stripe's scale, where training sets have thousands of features and billions of rows. Shepherd is the result. An engineer defines a feature once, and Chronon runs an offline (batch) job, a streaming job, and an online serving path, all reading and writing a key-value store that the adopter must supply.

  1. A two-tier KV store. Bulk historical uploads from offline jobs go to a cheaper write-once, read-many store. Streaming updates go to a more expensive distributed memcache-based store optimised for many writes and reads. Splitting by write pattern cut cost while meeting latency and freshness.
  2. Flink for streaming. By default Chronon's streaming job wrote each raw event into the KV store. Stripe chose Apache Flink for low-latency stateful processing. Chronon definitions are Python plus Spark SQL, and the online and offline paths must compute the same thing. Fortunately the Spark SQL used in feature definitions consists only of maps and filters: narrow transformations that work row by row with no shuffle. So Stripe implemented Spark SQL expression evaluation on Flink rows. Result: p99 freshness of 150 ms.
  3. Tiling for latency. With raw events in the store, serving a feature with many events means fetching and aggregating all of them, which is slow. Instead the Flink job keeps pre-aggregated partial values in state and periodically flushes them to the KV store. Each partial is a tile (for example the count and sum for one 5-minute slice). Serving a 7-day window then reads a few tiles instead of thousands of events. Stripe contributed both the Flink support and tiling back to Chronon.
  4. Offline at Stripe scale. Benchmarks showed Chronon's training-set generation scaled with predictable tuning knobs, including its handling of skewed data. Stripe integrated it with its customised Airflow: users mark a GroupBy as online or give a Join an offline schedule, and the needed jobs are scheduled automatically. Chronon assumed partitioned Hive tables, but many Stripe sources are unpartitioned snapshot tables, so Stripe added support for more source types and custom Iceberg writers to put features into the data warehouse for training and batch scoring.

First use: SEPA fraud. SEPA (Single Euro Payments Area) lets people and businesses make cashless euro credit transfers and direct debits across the EU. The Local Payment Methods team planned to mix new Shepherd features with legacy ones but found Shepherd easy enough to build a Shepherd-only model with over 200 features, both batch and streaming. Building it required modelling batch-data delay in training data: if a batch feature is only available with a day's delay in production, training rows must also see the day-old value, or the model learns from information it will never have at serving time. That mismatch is training-serving skew. With consistency monitoring and alerting in place, the model blocks tens of millions of dollars of additional fraud per year. Stripe is now a co-maintainer of Chronon with Airbnb (and designed its logo).

Overlooked constraints.

  • Point-in-time correctness. A training row for a payment at 10:00 must use feature values as they were at 10:00, not today's. Chronon's offline joins produce that; doing it by hand is the most common source of leakage.
  • Equivalence of two engines. Running the "same" SQL in Spark and Flink is only safe because the expressions are row-local. A feature needing a join or a shuffle would break the equivalence argument.
  • Tile size is a trade-off. Small tiles give accurate window edges but more reads; large tiles give fewer reads but a "7-day" window that is really "7 days give or take one tile".

What Stripe sacrificed. The simplicity of off-the-shelf use. Adopting Chronon early meant building the KV store, the Flink path, tiling, Airflow and warehouse integration, and taking on co-maintenance of an open-source project. In exchange Stripe got a single-definition feature platform and has passed most of its improvements back upstream.

Deep Dive: tiling arithmetic and the latency/freshness trade-offShow

Take a feature "charges per business over the last 7 days" for a large business that processes 2,000 charges per minute. A 7-day window has 2,000 × 60 × 24 × 7 ≈ 20.2 million events. Reading and summing 20 million events at serving time is impossible in a few milliseconds.

With 5-minute tiles, the window is 7 × 24 × 12 = 2,016 tiles. Better still, use hierarchical tiles: daily tiles for the 6 complete days, hourly tiles for the complete hours of the partial day, and 5-minute tiles for the most recent partial hour. That is at most 6 + 23 + 11 = 40 reads, plus the in-memory streaming partial that Flink has not yet flushed. Forty small KV reads, batched into one multi-get against memcache, fit in a millisecond or two.

Which aggregations tile? Tiling needs aggregations whose partial results can be combined: count, sum, min, max, and average (stored as sum plus count) all work. Distinct counts combine if each tile stores a sketch such as HyperLogLog (Lesson 11). Exact percentiles do not combine, but t-digest sketches approximately do. "Last value" combines if each tile stores a timestamp with its value.

Freshness budget. With p99 freshness of 150 ms, the path is roughly: event published to the stream (tens of ms), Flink applies the update to in-memory state (a few ms), and the serving path reads both flushed tiles and the live partial. If serving only read flushed tiles and the flush interval were 60 s, freshness would be up to 60 s. Getting to 150 ms means the most recent partial must be visible without waiting for the periodic flush. The post gives the 150 ms result, not this mechanism, so treat this breakdown as the handbook's reasoning about how such a target is reachable.

Training-serving skew from batch delay. If a batch feature is computed nightly at 02:00 and lands at 04:00, then a payment at 03:00 on day D sees the value computed from data up to the end of day D−2, not D−1. The training set must apply the same rule. Otherwise the model trains on fresher data than it will ever see and overestimates that feature's value. The general pattern is covered in ML System Design and Feature Stores.

Lesson 25: Real-time analytics for Stripe Billing#

Assumptions. Billing users watch subscription metrics in the Dashboard: monthly recurring revenue (MRR) growth, churn, trial conversion and more. A Stripe survey found 84% of business leaders saw fast pricing changes as a competitive edge in the next one to two years, which needs fresh data. The old pipeline was batch with an average 24-hour lag. The 2025 post (Reed Trevelyan) explains why subscriptions are awkward data: the current meaning of a subscription depends on its entire history. A $20 payment in June means little alone; the business needs to know the customer has paid on time every month since January. The old system recomputed each subscription's state from the beginning of time on every batch, which ruled out frequent runs.

Production architecture: three changes.

  1. An event-driven pipeline end to end. Updates to subscription and invoice objects become analytics events. Apache Flink keeps a highly compressed history per subscription as state and updates it incrementally, so the June $20 is simply appended to the running ledger instead of reprocessing everything since January. Bootstrapping state for long-standing customers would have meant replaying billions of historical events in order, so Stripe built a tool that runs the same streaming transformation logic as an Apache Spark job, processing history in parallel and writing verifiable flat files. That job produces the initial Flink state and also feeds a redundant offline pipeline for validation and data export.

  2. Query-time aggregation in Apache Pinot. The Dashboard lets users filter, group and drill down instantly. Showing MRR over time means knowing every subscription's state at every point in the chosen period. With Pinot as the OLAP database, the original design pre-aggregated this offline in a scheduled batch, which defeated real-time updates. Pinot's new v2 multi-stage engine supports windowed aggregation queries that compute values across many date ranges at query time, plus richer joins that enabled gap filling, currency conversion and custom dimensions. Stripe worked with Pinot maintainers to bring this engine to production; it had never been deployed in a user-facing context at Stripe's scale. Results: most updates processed in well under 1 minute, nearly all visible within 15 minutes, and query latency under 300 ms.

  3. Changing metric definitions without breaking consistency. Businesses define MRR differently, and Billing lets users change formulas (for example, exclude one-time coupons). For a customer since 2017 that means hours of reprocessing while new events keep arriving. The workflow:

    • Start a batch backfill that recomputes history under the new definition.
    • Meanwhile keep streaming new events under the old definition so the Dashboard stays live.
    • Buffer those incoming events in memory in the Flink app.
    • When the backfill finishes, patch Flink state with the recomputed history and replay the buffered events on top of it.
    • Switch the Dashboard to the new numbers and stop the old-definition processing.

    The Dashboard is never greyed out and never shows a mix of definitions. Next steps: lower latency still, plus usage-based metrics and geography and cohort filters.

Connecting to the classic batch design. The interview version of this problem is the ad-click aggregator, where the "good but not great" answer is a separate analytics database fed by batch jobs. Raw click events go into a write-optimised store (an LSM-based database such as Cassandra). A Spark job runs every few minutes, reads the new events, aggregates by ad and minute, and writes rows like (ad_id, minute, clicks) into a columnar OLAP store that answers dashboard queries quickly. Volume is manageable: at 10,000 clicks per second, a 5-minute batch is 3 million events, roughly 300 MB at about 100 bytes each. A time-series database is a weaker fit because advertisers slice by many high-cardinality dimensions (campaign, country, device). The weaknesses are exactly those Stripe hit: freshness is bounded by the batch interval plus run time, and if a batch overruns its interval, jobs queue up and lag grows. Putting a queue in front of the batch adds durability but does not fix latency. The better answer is a stream processor (Kafka plus Flink) with event-time windows, watermarks for late data and checkpointed, exactly-once state, writing to the OLAP store continuously. Stripe Billing's redesign is that progression applied to subscriptions, with one twist: the state is a long history per subscription rather than a short click window. More on the general pattern: Ad Click Aggregator and Apache Flink.

Overlooked constraints.

  • Bootstrapping state is its own project. A streaming job cannot start from nothing when customers have nine years of history. Running the same logic in batch to build initial state, and checking that both paths agree, is the standard answer.
  • Definition changes are schema migrations. Changing a metric formula is like changing a column's meaning; it needs the same backfill, dual-run and cutover discipline as Lesson 8's online migrations.
  • Buffering has a memory ceiling. Events buffered during a long backfill sit in Flink memory (or state). If a backfill takes many hours for a big customer, that buffer must be sized, or spilled to durable state.
  • Query-time aggregation shifts cost to reads. Removing pre-aggregation makes every Dashboard query do more work. It works because Pinot's columnar storage and indexes are built for it, and query latency must be watched as data grows.

What Stripe sacrificed. Operational simplicity. One batch job became a Flink pipeline, a Spark job that mirrors its logic, a validation pipeline, a new Pinot engine version and a backfill-and-patch workflow. In exchange, data lag fell from about 24 hours to minutes.

Deep Dive: why incremental state wins, and what a definition change costsShow

Full recompute versus incremental. Suppose (handbook's illustration) a business has 200,000 subscriptions with an average of 40 historical invoice and change events each: 8 million events. Recomputing everything costs O(8M) work per run. With 20,000 businesses of varied size, a full recompute of everyone touches billions of events, so running it every 15 minutes is infeasible. Incremental processing costs O(new events): if this business sees 2,000 changes a day, Flink does about 2,000 small state updates a day for it. That is a 4,000-fold reduction in work per day, which is the core reason the 24-hour lag could drop to minutes.

State size. If compressed subscription state averages 500 bytes and Stripe Billing tracks (illustratively) 500 million subscriptions, state is about 250 GB. That is large but well within Flink's RocksDB-backed state with incremental checkpoints, spread across many task slots.

Cost of a definition change. For the 2017 customer, reprocessing 8 million events in a Spark job at 200,000 events per second per executor across 10 executors takes about 4 seconds of pure compute. In practice reading, shuffling and writing state dominate, which is why the post speaks of hours. Meanwhile the live stream keeps running. If that business generates 2,000 changes a day and the backfill takes 3 hours, about 250 events are buffered, which is trivial. For the largest customers with millions of events per day the buffer is much bigger, so it must be bounded and, if needed, kept in durable state rather than heap memory.

Windowed aggregation at query time. "MRR by month for the last 24 months" means, for each of 24 month-ends, summing each active subscription's monthly-normalised amount at that moment. If each subscription's state changes are stored as rows (sub_id, valid_from, valid_to, mrr), the query becomes, for each month-end t, the sum of mrr where valid_from <= t < valid_to. A columnar engine scanning a few million rows per business with this predicate returns in well under a second, which is consistent with the reported sub-300 ms latency. (The row layout is the handbook's illustration.)

Lesson 26: Selective Test Execution for a 50-million-line Ruby monorepo#

Assumptions. Stripe's Ruby monorepo is on the order of 50 million lines, with about 100,000 test files and 1.2 million test units. Run one after another, a full build would take four months. Builds run on a massively parallel worker fleet, about 50,000 builds a week, and the rate is rising as AI tools speed up commits. The 2026 post (Aditya Anchuri) describes Selective Test Execution (STE): on average about 5% of the Ruby suite runs per build, with a median of 0.5%, for less than 10% of the compute of running everything, without losing safety. A typical change runs a few hundred tests.

Why static analysis isn't enough. Static dependency analysis (parse source, follow imports) works in languages with explicit module boundaries, and Stripe uses it for some codebases. Ruby has escape hatches: metaprogramming and dynamic dispatch, configuration and environment that pick branches at runtime, and tests that depend on non-Ruby files (YAML, JSON, templates, fixtures, generated code). Predicting exactly what a test will execute is impossible in general. Approximations either underselect (skip a test that should run, which is dangerous) or overselect (run close to everything, which is slow).

Production architecture: record what tests actually touched.

  1. file_access_interceptor. An in-house C++ shared library loaded with LD_PRELOAD. It intercepts open system calls (and variants), records which file was opened under which scope (the test runner sets the scope to the current test file), and propagates LD_PRELOAD into child processes so forks and subprocesses are still attributed. Inside the hot path it only appends a record to a per-process log in a temp directory; aggregation and indexing happen elsewhere. In an interpreted language every code or config file a process depends on must be opened at some point, which makes file opens a complete signal, unlike compiled languages where sources are baked into binaries.
  2. Scopes. Every process starts in the root scope r. When the runner forks to run a test file it pushes a scope like //r/file-/cibot/test/tasks/cancel_build_test.rb. A test file depends on files opened in its scope and its parent scopes. Anything opened in root scope is therefore a global dependency: change it and every test runs. Stripe treats this as honesty, not a bug; the runner deliberately preloads core primitives at root for speed, so changes to them really should trigger everything.
  3. The selection index. Workers stream results and indexed open-file logs to the build scheduler (a sidecar that distributes tests). The scheduler inverts them into "file → test files that opened it" and writes the selection index at the end of the build: a roaring bitmap per file, keyed by the file's numeric index, whose bits are the test files to run. About three billion data points are stored and queried quickly. Roaring bitmaps (Chambi, Lemire, Kaser and Godin, "Better bitmap performance with Roaring bitmaps", 2016) split the integer space into 65,536-value chunks and store each chunk as either a sorted array (sparse) or a plain bitmap (dense), so unions and intersections are fast and memory stays small.
  4. The file inventory and hashdeep. Git diffs are not enough, because tests also depend on generated files produced by code generation before tests run. Each build records an inventory of every file with its content hash from hashdeep, a parallel hashing tool. A new build computes its inventory, compares it with the baseline build's, maps changed files to indexes, and unions their bitmaps.
  5. Guardrails. Always rerun previously failing tests. Always run mandatory tests that use directory globbing or file discovery, because adding a new file changes their behaviour without any earlier open signal (mostly codebase-health and lint tests). Give linters such as RuboCop or YAML lint the changed-file list so they lint selectively instead of scanning the repo.
  6. A fast, reproducible baseline. Build completion state and metadata are stored in MongoDB and ordered by Monotonic Revision IDs (MRIs): strictly increasing ids with the property that if commit A is an ancestor of B then MRI(A) < MRI(B). One query keyed by MRI finds the latest completed STE dataset, the STE base, without walking git history at build start. That makes selection fast and makes "which baseline did you use?" a recorded, replayable input.

The four reusable rules the post ends with. Choose a dependency signal that survives language dynamism (file access). Capture it at an efficient boundary (the syscall), not a noisy one (per-line tracing). Store and serve it so that operations scale (one query, monotonic ordering, reproducible baselines). Add pragmatic guardrails for the edge cases engineers actually hit.

Overlooked constraints.

  • Data, not just code, can change behaviour. A test that reads a database row or a remote service response depends on something no file hash captures. File-level selection is sound only to the extent tests are hermetic.
  • The baseline can be stale. If the latest completed STE base is several commits behind, the diff includes all intervening changes, so selection grows. That is safe (overselection), but builds get slower when baselines lag.
  • New tests have no history. A newly added test file has never been recorded, so it must always run, which a changed-file check gives naturally because the test file itself is new.
  • Root-scope creep. Each file opened at root widens the blast radius of every change to it. Keeping root-scope preloads small is a continuous discipline.

What Stripe sacrificed. Absolute certainty and some engineering investment. A syscall interceptor, a distributed indexing pipeline and a guardrail list are more complex than "run everything". STE also accepts a small, explicitly managed residual risk (non-hermetic tests) for a more than 10x compute saving and minute-scale CI.

Deep Dive: the compute arithmetic and why bitmaps fitShow

Four months, sequentially. 4 months ≈ 120 days ≈ 10.4 million seconds. Spread over 1.2 million test units, that is about 8.6 s per unit on average, including setup. To finish a full run in 10 minutes (600 s) you would need about 17,000 workers per build. At 50,000 builds a week, that would be 50,000 × 10.4M s ≈ 5.2 × 10¹¹ worker-seconds a week, or about 860,000 always-busy workers. Running 5% on average cuts that to about 43,000. That is why STE is not a nicety but the only feasible way to run CI at this scale. (Derived from the post's figures; real costs depend on parallel efficiency.)

Mean 5% versus median 0.5%. The distribution is heavily skewed: most changes touch leaf files used by a few tests, while a few touch shared or root-scope files and select a large fraction. So the mean is dominated by the rare big builds. Shrinking root-scope dependencies lowers the mean much more than optimising typical builds.

Why roaring bitmaps. There are about 100,000 test files, so a per-file set of tests is a subset of [0, 100,000). A plain bitset is 12.5 KB per source file. Across, say, a few million inventory files that would be tens of GB, and most of it would be zeros, because most files are used by only a few tests. Roaring stores sparse chunks as small sorted arrays (2 bytes per entry), so a file used by 30 tests costs about 60 bytes plus a header. Unioning the bitmaps of 50 changed files is then a fast merge of small arrays and occasional dense chunks. Three billion (file, test) pairs at about 2 bytes each is roughly 6 GB before compression, which fits comfortably in memory on one large machine.

MRI ordering. One simple way to get "ancestor implies smaller id" on a trunk-based monorepo is to number commits as they land on main: every ancestor landed earlier, so it has a smaller number. Then "latest completed base at or before my commit" is max(mri) where mri <= my_mri and status = complete, one indexed query. (The post states the property, not the generation method; this is one way to satisfy it.)

Lesson 27: Jurisdiction resolution for Stripe Tax#

Assumptions. Stripe Tax calculates tax in 100+ countries. The US is the hardest: there are more than 16,000 combinations of sales-tax rates and rules that can apply to an online purchase depending on location, and the boundaries change constantly. The 2025 post (Erich Rentz and Danko Komlen) describes the patent-pending jurisdiction resolution system (JRS), which finds the right taxing jurisdictions for a US transaction within a few milliseconds, in-house rather than outsourced, so Stripe controls accuracy and reliability.

Postal addresses are not enough. Two houses in Drexel, Missouri, share a city, a ZIP code and nearly the same house number, yet sit in different counties with different tax. The address alone cannot tell them apart. The answer is geometry: geocode the address to a point and find which jurisdiction polygons contain it. Two barriers stand in the way. Public boundary data is inaccurate and inconsistent across authorities; a few inches of error misassigns addresses, and neighbouring jurisdictions must tile the map with no gaps and no overlaps. And the polygons are complex, with hundreds or thousands of edges and holes ("islands" that are excluded, as in the map of Sandy, Utah), so testing containment near boundaries is expensive.

Production architecture: offline regions, online lookup.

Offline: build SPOTs. A Stripe GIS (geographic information system) cleans, centralises and standardises boundaries for 53 "states" (counting Puerto Rico, the Virgin Islands and Washington, DC), 3,225 counties, about 10,000 cities and about 3,000 districts. Layers are overlaid in order of difficulty: states (never overlap), counties (never cross states), then cities (can cross counties) and districts (can cross cities, counties and other districts). Every region with a unique combination of overlapping authorities is a Stripe place of taxation (SPOT): every transaction inside one SPOT owes the same state, county and local taxes. When boundaries change, the SPOTs for that state are recomputed, new SPOTs are tagged with the effective time, and old SPOTs are kept with their end time. SPOTs are therefore time-aware: Stripe can calculate tax for now and recalculate past transactions correctly.

Online: point to SPOT. There are over 166 million US mailing addresses and about 16,000 SPOTs, so precomputing every address's SPOT is impractical; matching happens on demand. The JRS replaces each complex SPOT with its bounding box (min and max x and y). One box may cover several jurisdictions, so boxes are nested inside boxes in a balanced R-tree (Guttman, "R-Trees: A Dynamic Index Structure for Spatial Searching", 1984), rebuilt with Sort-Tile-Recursive (STR) bulk loading (Leutenegger, Lopez and Edgington, 1997) whenever data changes. A lookup descends from the state's box through smaller boxes to a final box containing only a few candidate SPOTs, and only then runs an exact point-in-polygon test on those few. Two optimisations fixed slow outliers: check smaller boxes first at each level (they tend to be dense urban areas, where most requests come from), and split disjoint SPOTs into separate parts (imagine one box per Hawaiian island instead of one box around the whole chain). Result: p95 under 10 ms in every state except South Carolina, where the Charleston area is unusually complex; Charleston alone has 73 disjoint areas. Time-awareness also handles changes taking effect at midnight in the right local time zone.

Overlooked constraints.

  • History costs memory. Keeping every past SPOT for recalculation means the data grows forever. Stripe names this as an open problem.
  • Geocoding is an error source too. If the address is geocoded a few metres to the wrong side of a boundary, a perfect polygon test still gives the wrong tax. Boundary-adjacent points deserve extra scrutiny.
  • Bounding boxes overlap. Unlike SPOTs, boxes in an R-tree can overlap, so a lookup may need to descend several branches. STR packing reduces overlap, which is why it matters for worst-case latency.
  • Topology must be valid. The no-gap, no-overlap property is what makes "exactly one SPOT contains this point" true. Without it, a point could fall into zero or two SPOTs.

What Stripe sacrificed. Simplicity and outsourcing. Building a GIS, curating boundaries and tracking every tax change in-house is expensive. Stripe chose to own the accuracy and latency of a calculation that sits in the checkout path.

Deep Dive: cost of point-in-polygon and what the R-tree buysShow

The exact test. The standard ray-casting test draws a ray from the point and counts how many polygon edges it crosses: odd means inside. It costs O(n) for a polygon with n edges. A complex SPOT may have thousands of edges, and if you tested every SPOT in a state with, say, 1,000 SPOTs averaging 2,000 edges each, that is 2 million edge checks per lookup. At around 5 ns per check that is about 10 ms on one core, too slow and too costly at checkout volume, and the cost gets worse near boundaries where floating-point care is needed.

With an R-tree. With fan-out 50, a tree over 16,000 SPOT parts has about log₅₀(16,000) ≈ 2.5, so 3 levels. A lookup checks about 50 box corners per level (cheap comparisons), then runs ray casting on perhaps 3 candidate polygons: about 3 × 2,000 = 6,000 edge checks, around 30 µs. That is two to three orders of magnitude less work, consistent with the few-millisecond end-to-end latency once geocoding and data access are included.

Why split disjoint SPOTs. A SPOT made of 73 islands spread across a metro area has one huge bounding box that overlaps many other SPOTs' boxes, so lookups anywhere nearby land on it as a candidate and pay for its full edge count. Splitting it into 73 parts gives 73 small, tight boxes. Most lookups then touch none of them, or only one small part.

Why STR. Inserting rectangles one at a time builds a tree whose quality depends on insertion order. STR sorts all rectangles by x, cuts them into vertical slices of about √(N/B) groups (B being node capacity), sorts each slice by y, and packs nodes full. The result has near-100% node fill and low overlap, and it is cheap to rebuild because the data changes only when tax boundaries do. The same family of spatial indexes underpins proximity services; see Geospatial Indexing and Proximity Service.

When to Use It#

Stripe's posts are most useful when your system has one of these properties:

  • Clients retry writes that move money or create resources. Idempotency keys on the server (Lesson 1), stable keys derived from a server-side id on the client (Lesson 20), and a queue so retries actually happen.
  • A public API that thousands of integrations depend on. Date-based versions pinned per account plus version change modules (Lesson 3), a single machine-readable spec that drives docs and SDKs (Lesson 4), and PaymentIntent-style state machines for multi-step flows (Lesson 2).
  • Shared capacity with bursty, uneven clients. Four layers of rate limiting and load shedding (Lesson 5), client-side spacing and concurrency limits (Lesson 6), and fetch-before-process with throttled webhook queues (Lesson 7).
  • A schema or database change on a live, critical table. Dual write, backfill, read cutover and cleanup (Lesson 8); for whole shards, a coordinated traffic switch with a short write pause (Lesson 9).
  • Financial or regulated data that must be explainable to auditors. An immutable double-entry ledger with clearing, timeliness and completeness metrics (Lesson 16), logical accounts guarded from real cash (Lesson 18), and a logical/physical split for promises made to users (Lesson 21).
  • Two systems that must agree but are owned by different organisations. Per-attribute ownership, durable queues, content-hash idempotency, tombstones and a periodic deep reconciliation (Lesson 17).
  • Observability that cannot answer new questions. Canonical log lines (Lesson 10) and a fleet-wide metrics aggregation tier with mergeable sketches (Lesson 11).
  • Low-latency ML in a request path. A DNN with explanation tooling (Lesson 22), a central training API (Lesson 23), and tiled, streaming features with point-in-time training data (Lesson 24).
  • Analytics that lag by a day. Incremental stream state bootstrapped from batch, query-time windowed aggregation, and backfill-then-patch for definition changes (Lesson 25).
  • CI that costs more every month. Dynamic, file-level test selection (Lesson 26).
  • A lookup by location inside a checkout. Offline region precomputation plus an online R-tree (Lesson 27).

When NOT to Use It#

  • Pinned-per-account API versioning for an internal API with three callers. Coordinate a change and deploy it; version change modules are worth it only when you cannot upgrade your clients.
  • A full double-entry ledger for a product that never moves money. Event sourcing or plain audit logs give traceability with far less modelling effort.
  • Building your own data plane proxy, DNS tier or KV-store layer at small scale. Stripe did so above 1.6% of global GDP and a 99.9995% target. Off-the-shelf Envoy, managed DNS and a managed cache are the right answer for nearly everyone else.
  • Selective test execution for a suite that runs in 10 minutes on a few machines. The interceptor, index and guardrails pay off only when full runs are prohibitively expensive.
  • Streaming analytics when a daily report is fine. Lesson 25's pipeline is much more complex than a nightly batch; buy it only when freshness is worth money.
  • Treating snapshot events as the source of truth. If you need the latest state, use events as triggers and fetch (Lessons 7 and 19), rather than building on a stream of possibly stale payloads.

How to Implement It#

A practical order for applying these lessons to a payments-like service:

  1. Make every mutating endpoint idempotent. Store (account, key) → request hash, response, status before doing side effects, reject the same key with a different body, and keep keys for at least 24 hours (Lessons 1 and 20).
  2. Model multi-step operations as explicit state machines with documented transitions, like PaymentIntent's statuses (Lesson 2) and GPTNWorkflows (Lesson 21).
  3. Version the public API from day one. Pin each account to the version it first used, write each breaking change as a small transformation that converts new responses to old ones, and generate docs and SDKs from one spec (Lessons 3 and 4).
  4. Add rate limits in layers. Per-user request rate, per-user concurrency, a fleet-wide shedder that reserves capacity for critical traffic, and a worker-utilisation shedder (Lesson 5). Return 429 with a clear reason and teach clients to back off with jitter (Lesson 6).
  5. Emit one canonical log line per request with ids, timings, status, user and version, and push metrics through a local aggregator that forwards mergeable sketches (Lessons 10 and 11).
  6. Record money in an append-only double-entry ledger using integer minor units. Alert on clearing accounts that stay non-zero past their expected clearing time, on late data, and on ids missing from the ledger (Lesson 16).
  7. Put a durable queue and a DLQ in front of every external call that must eventually happen, sync to partners at a fixed rate under their limits, and run a periodic deep reconciliation (Lessons 7, 17 and 20).
  8. Plan schema changes as four phases: dual write, backfill and verify, switch reads, remove the old path, each reversible until the last (Lesson 8).
  9. Separate logical promises from physical execution. Expose stable balances and dates to users, hold buffers and circuit breakers for the physical side, and keep "logical" accounts unable to move real cash (Lessons 18 and 21).
  10. Automate operations as graph search over states (Lesson 14), and run an honest RCA after every incident (Lesson 15).

The snippet combines Lessons 1, 16 and 20: an idempotent ledger posting that checks the request fingerprint, enforces the double-entry invariant and runs in one transaction.

type Posting = { account: string; amountMinor: bigint; currency: string };
 
async function postEntry(db: Db, acct: string, key: string, body: { postings: Posting[] }) {
  const fingerprint = sha256(canonicalJson(body));
  return db.transaction(async (tx) => {
    const prior = await tx.idem.find({ acct, key });          // unique (acct, key)
    if (prior) {
      if (prior.fingerprint !== fingerprint) throw new HttpError(422, "key reused with new body");
      return prior.response;                                   // replay, no new side effect
    }
    const byCurrency = new Map<string, bigint>();
    for (const p of body.postings) {
      byCurrency.set(p.currency, (byCurrency.get(p.currency) ?? 0n) + p.amountMinor);
    }
    for (const [cur, sum] of byCurrency) {
      if (sum !== 0n) throw new HttpError(400, `entry does not balance in ${cur}`);
    }
    const entryId = await tx.entries.insert({ acct, createdAt: tx.now() });
    await tx.postings.insertMany(body.postings.map((p) => ({ entryId, ...p })));
    const response = { entryId, status: "posted" };
    await tx.idem.insert({ acct, key, fingerprint, response, expiresAt: tx.now() + DAY_MS });
    return response;                                           // all or nothing
  });
}

Storing the key, the postings and the response in one transaction is what makes the operation safe: a crash before commit leaves nothing, and a crash after commit lets the retry find the stored response.

TechnologyFits when
PostgreSQL or MySQL with unique constraintsIdempotency keys and ledger postings that need atomic insert-if-absent
MongoDB-based DocDB-style sharded storeLarge document data with a migration platform that moves chunks between shards (Lesson 9)
Redis token bucketsPer-user rate limits and concurrency counters at low latency (Lesson 5)
OpenAPI with vendor extensionsOne spec that generates docs, SDKs and CLI (Lesson 4)
Kafka, SQS, EventBridgeDurable queues and event fan-out for sync and webhooks (Lessons 7, 17, 20)
TemporalLong-running remediation and money-movement workflows with retries and state (Lesson 14)
FlinkStateful stream processing for features and analytics (Lessons 24, 25)
Apache PinotSub-second OLAP queries over fresh data with windowed aggregation (Lesson 25)
Spark with IcebergBackfills, state bootstrapping and training-data generation (Lessons 24, 25)
Presto or TrinoAd-hoc investigation of ledger and data-quality issues (Lesson 16)
Kubernetes with affinity and tolerationsMixed CPU, memory and GPU training jobs (Lesson 23)
Roaring bitmapsLarge sparse set unions, such as file-to-test indexes (Lesson 26)
R-tree with STR bulk loadingPoint-in-region lookup over complex, slowly changing polygons (Lesson 27)

Trade-offs#

LessonGainCost
Idempotency keysSafe retries for money-moving callsKey storage, a 24-hour horizon, fingerprint checks
PaymentIntents state machineOne API for every payment method and flowMore states for integrators to handle
Version change modulesNever break an existing integrationEvery change written twice: new shape and backwards transform
Layered rate limitersProtect shared capacity, critical traffic firstSome legitimate requests get 429s and must retry
Online migrationsSchema change with no downtimeWeeks of dual writes, backfill and verification
DocDB traffic switchShard moves with sub-second write pauseComplex coordination, versioned routing, a custom platform
Canonical log linesAny question answerable from one lineLog volume and a schema discipline across services
VeneurCorrect global percentiles and fewer agentsAnother tier to run; sketches are approximate
Custom data plane proxy99.9995% target with hedging and fast configOwning a proxy instead of using Envoy
Ledger and DQ99.9999% explainable money movementEvery producer models a fund flow; days to fully verify
Logical accountsCredits reuse real money infrastructurePlatform guardrails and two funds flows to maintain
Thin eventsUpgrade-proof event handlingOne API read per event
Global money platformNew regions in weeks, consistent semanticsProduct teams depend on a central platform
DNN-only Radar85% faster training, scales with dataHarder to explain, needs separate tooling
Shepherd tiling150 ms freshness with fast readsFlink, two KV tiers and engine equivalence to maintain
Streaming billing analyticsMinutes instead of 24 hoursFlink, Spark mirror, Pinot v2 and backfill workflow
Selective testsUnder 10% of full CI computeInterceptor, index and a residual risk for non-hermetic tests
JRSCorrect tax in millisecondsIn-house GIS, history storage that keeps growing

Common Pitfalls#

  • Generating idempotency keys per request instead of per action. Two taps on "Pay" become two keys and two charges. Derive keys from a server-side checkout or order id.
  • Retrying without the original key in a queue worker or proxy. The retry is a brand-new charge.
  • Treating "the API returned 200" as synced. Without durable records and a periodic reconciliation, drift is invisible until a customer complains.
  • Hard-deleting records that another system mirrors. Without tombstones, the other side cannot tell "deleted" from "never synced".
  • Storing money as floating point. Use integer minor units and enforce a balanced-entry invariant on every write.
  • Letting a "virtual" balance into cash processes. Logical accounts must be excluded from transfers to real accounts and from sweeps, enforced by the platform.
  • Shipping a breaking API change behind a flag instead of a version. Flags multiply untested combinations; versions give each integration one stable contract.
  • Health checks that ask "are you alive?" but not "are you making progress?". Lesson 15's stalled replicas passed health checks for four days.
  • Training on features fresher than production will see. Model batch delays in training data or accept training-serving skew.
  • Making a streaming pipeline the only copy of the logic. Keep a batch path with the same logic for bootstrap, validation and backfills.

Real-World Examples#

All from the fetched Stripe posts:

  • Black Friday to Cyber Monday: 300 million transactions and $18.6B in payment volume with the API above 99.999% availability; Ledger handles about five billion events a day and explains over 99.9999% of money movement (Lesson 16).
  • DocDB serves more than five million queries per second across thousands of shards and moves data between shards with the Data Movement Platform without downtime (Lesson 9).
  • The data plane proxy targets 99.9995% reliability for traffic that grew beyond 1.6% of global GDP (Lesson 13).
  • The 2019-07-10 incident: two windows of API degradation, 16:35 to 17:02 and 21:14 to 22:47 UTC, caused by a failover bug with stalled nodes and then a rollback interacting with a configuration change (Lesson 15).
  • Radar evaluates over 1,000 signals in under 100 ms and wrongly blocks about 0.1% of legitimate payments; dropping XGBoost for a ResNeXt-style DNN cut training time by over 85% (Lesson 22).
  • Shepherd powers a SEPA fraud model with over 200 features that blocks tens of millions of dollars of additional fraud a year, at p99 feature freshness of 150 ms (Lesson 24).
  • Billing analytics went from a 24-hour average lag to as low as 15 minutes with under-300 ms queries (Lesson 25).
  • Selective Test Execution runs about 5% of 1.2 million Ruby test units per build on average, for under 10% of the compute, across about 50,000 builds a week (Lesson 26).
  • The Global Money Management Platform cut regional launches from about a year (US, UK) to three months (EU) and six weeks (Australia) (Lesson 21).

In the Interview#

Deep Dive: designing a small payments platform with Stripe's lessons, with numbersShow

Take a hypothetical marketplace: 2,000 payments per second at peak, 50 million payments a month, 30 currencies, a public API used by 10,000 sellers, and payouts in 12 countries.

Idempotency storage. 2,000 writes/s × 86,400 s ≈ 173 million keys a day at peak rate (roughly 1.7 million a day at the monthly average of about 19 per second, so peak is the sizing case). At about 1 KB per stored key and response, a 24-hour window at peak is around 170 GB. That fits in a sharded relational store or a key-value store with TTL. Key on (seller_account, key) so tenants cannot collide.

Rate limits. Give each seller 100 requests/s with burst 200 and 20 concurrent requests. Reserve 20% of fleet capacity for critical payment creation and confirmation, and shed analytics and list endpoints first when utilisation passes 80% (Lesson 5).

Ledger volume. Each payment produces about 4 postings (authorisation, capture, fee, payout clearing): 200 million postings a month, about 2.4 billion a year. At 80 bytes per row that is about 190 GB a year, which is comfortably partitioned by month. The clearing query runs hourly over recent partitions; the full-history query runs nightly.

Data-quality targets. At $3B a month of volume, a 99.9999% explainability target leaves $3,000 a month unexplained, an amount a single analyst can investigate. A 99.99% target would leave $300,000, which needs a team.

Webhooks and sync. Sellers receive thin events and fetch the object. At 2,000 payments/s with 3 events each, that is 6,000 notifications/s. Tell sellers to coalesce by object id and fetch at a throttled rate, and budget the API for an extra 2,000 to 6,000 reads/s (Lessons 7 and 19).

Payout promises. Promise T+2 in every country, but measure each rail's settlement-time tail and hold a buffer sized for common slips (for example the 99th percentile of daily late volume), plus a circuit breaker that pauses payouts in a corridor if late volume exceeds the buffer (Lesson 21).

Migrations. Moving the payments table to a new schema at 2,000 writes/s: dual writes add about 2,000 writes/s, and the backfill of 1 billion historical rows at 5,000 rows/s takes about 2.3 days. Plan for a week including verification (Lesson 8).

None of these numbers are Stripe's; they show how to derive your own from the same rules.

Key Takeaways#

  • Every API call that moves money must be safe to retry: store an idempotency key with its result in the same transaction as the side effect, and derive the key from the action, not the request.
  • A queue makes sure a payment attempt happens and an idempotency key makes sure it happens once; you need both.
  • Model multi-step payments as explicit state machines and pin each API consumer to a version, translating responses backwards through small, isolated version change modules.
  • Protect shared capacity with several layers of rate limiting and load shedding, and reserve capacity for the most critical traffic.
  • Change live schemas and move live data in reversible phases (dual write, backfill and verify, switch reads, clean up) rather than in one risky cutover.
  • One wide, structured log line per request and mergeable metric sketches give observability that answers questions you did not plan for.
  • An immutable double-entry ledger turns financial correctness into measurable numbers: clearing, timeliness and completeness.
  • Separate logical promises to users from physical cash movement, and make logical-only balances unable to trigger real money movement by platform rule.
  • Thin events plus fetching current state make webhooks upgrade-proof and ordering-safe, at the cost of an extra API read per event.
  • Streaming systems need a batch twin with the same logic for bootstrap, validation and backfills, whether for billing analytics or ML features.
  • At large scale, record what actually happens, such as files tests open or features at prediction time, instead of predicting it statically.