A million and a half invoices a day
Generating, numbering and signing tax documents at marketplace scale, where a duplicate is a legal problem and a gap is an audit question. Notes from building invoicing at Flipkart.
Between 2016 and 2018 I worked on the systems at Flipkart that produced invoices and signed documents for orders leaving the marketplace. On a normal day that meant somewhere around a million and a half documents. On a sale night it meant most of those arriving in a few hours.
Invoices are a strange engineering problem. The throughput isn't extreme by internet standards. What makes them hard is that the rules are unusually strict and unusually unforgiving. A web page rendered twice is a cache miss. An invoice generated twice is two legal documents for one sale. A notification number skipped is nothing. An invoice number skipped is a question from an auditor, and you'd better have an answer.
This is a write-up of how we thought about it, what broke, and what I'd keep.
What an invoice actually has to be
Before any architecture, it's worth writing down the constraints, because every design choice falls out of them.
- Exactly one per shipment. Not per order — an order can split into several shipments from different sellers and warehouses, and each one needs its own invoice.
- Numbered in a strict sequence. Within a series — roughly, one legal seller entity, one registration, one financial year — numbers must be consecutive. No duplicates, no gaps.
- Immutable once issued. You never edit an invoice. A mistake is corrected with a credit note that references it.
- Signed. The document carries a digital signature so anyone can verify it wasn't altered.
- Ready before the parcel leaves. The invoice travels with the shipment. A package can't be handed to the courier without one.
- Retained. For years, in a form you can produce on request, unchanged.
Notice that throughput isn't on the list. It's implied by number five, and it's the reason the other five are hard.
The pipeline
We broke generation into stages, each with its own state, each safe to retry.
Five stages, one row per shipment. A worker can die at any arrow and the next one resumes from the stored state.
The important idea is the single invoice row per shipment, with an explicit state. Every worker does the same thing: find rows in the state it handles, do its step, and move the row forward with a compare-and-set. If two workers grab the same row, one of them loses the update and moves on.
update invoices
set state = 'rendered',
pdf_ref = :pdf_ref,
attempt = attempt + 1,
updated_at = now()
where id = :id
and state = 'numbered' -- only advance from the state we read
returning id;No row returned means someone else got there first. That's not an error; it's the system working.
Idempotency starts with the request
The first stage is the one people get wrong, because it looks trivial. The order management system tells us a shipment is ready to be invoiced. We create a row.
The OMS will tell us more than once. It retries on timeouts. It replays after incidents. During one migration it replayed a full day. The only safe way to handle that is to make the shipment itself the identity of the request.
public InvoiceRef handle(ShipmentReady event) {
String key = event.sellerEntityId() + ":" + event.shipmentId();
Optional<Invoice> existing = invoices.findByRequestKey(key);
if (existing.isPresent()) {
return existing.get().ref(); // replay: same answer, no new work
}
try {
Invoice inv = Invoice.requested(key, event);
invoices.insert(inv); // unique index on request_key
return inv.ref();
} catch (DuplicateKeyException race) {
return invoices.findByRequestKey(key).orElseThrow().ref();
}
}The unique index does the real work. The lookup before it is an optimisation so replays don't throw exceptions by the thousand. The catch handles two copies of the same event arriving at the same moment on two machines, which at our volume happened every single day.
Gapless numbering is a locking problem
This is the part that took the most thought.
A database sequence is the obvious way to hand out numbers. It's fast, it's concurrent, and it's exactly wrong for invoices. Sequences are deliberately non-transactional: if the transaction that took number 1003 rolls back, 1003 is gone forever. That's fine for primary keys. For invoices it leaves a hole, and a hole needs explaining.
A number should only exist if the invoice it belongs to exists. Same transaction, or not at all.
The fix is to keep the counter in a row and increment it in the same transaction that writes the invoice number. If anything fails, both roll back together. Either the invoice got 1003 and the counter says 1003, or neither happened.
def allocate_number(tx, invoice_id: str, series: Series) -> str:
"""Assign the next number in the series. Must run inside the caller's transaction."""
row = tx.execute(
"""
update invoice_series
set next_value = next_value + 1
where series_key = %s
returning next_value - 1 as value, prefix
""",
(series.key,),
).one()
number = f"{row.prefix}-{row.value:07d}"
tx.execute(
"update invoices set number = %s, state = 'numbered' where id = %s and state = 'requested'",
(number, invoice_id),
)
return numberThe cost is obvious: that update takes a row lock, and every invoice in the series waits for it.
One series for the whole marketplace would have serialised a million and a half transactions a day
through a single row.
The way out is that the rules don't require one global sequence. They require a sequence per series, and a series is naturally narrow: one seller entity, one registration, one document type, one financial year. Split along those lines and you have hundreds of independent counters, each one hot only for its own seller. The busiest series still saw contention on sale days, so we kept the numbering transaction tiny: lock, increment, write the number, commit. Rendering and signing happen afterwards, outside the lock.
Two rules came with this design and were enforced in code review, not just documentation:
- Nothing slow inside the numbering transaction. No network calls, no rendering, no logging to a remote service. If it can block, it goes after the commit.
- Cancellations never reuse numbers. A cancelled shipment after numbering gets a credit note. The number stays used, with a document that explains it.
Rendering: boring on purpose
Turning an invoice record into a PDF sounds like the expensive part. In practice it was the easiest stage to scale, because it's stateless. A pool of workers takes numbered invoices, fills a template, renders a PDF, stores it, and advances the row.
The lessons here were about reproducibility rather than speed.
Pin the template version on the invoice. If a template changes at noon, an invoice numbered at 11:59 and rendered at 12:01 must still use the 11:59 template. Otherwise two copies of the same invoice, rendered at different times, can differ. We stored the template version in the row at numbering time.
Fonts are dependencies. We had an incident where a base image update changed a fallback font, and a batch of invoices in one regional language rendered with missing glyphs. Nothing errored. The PDFs were valid; they were just wrong. After that, fonts were vendored with the templates and a small set of golden invoices were rendered and compared in CI on every change.
Render once. Re-rendering an already-signed invoice "to fix something" is not allowed. If the data was wrong, that's a credit note and a new invoice.
Signing is the bottleneck, and that's fine
Every document is signed with the seller's key, and those keys live in hardware security modules. That's the right place for them. It also means signing is the one stage you can't just scale by adding machines: HSM throughput is fixed, expensive to extend, and shared.
At normal load it wasn't a problem. At sale load it was the only problem.
We made three changes, in order of how much they helped.
Sign hashes, not documents. Sending a whole PDF to the signing service and back is wasteful. We computed the digest on the render worker and sent only that. The HSM does the small, slow, secret part; everything else stays outside.
Batch. HSM operations have a fixed overhead per call. Grouping digests for the same key into batches, and flushing on size or a short timer, multiplied effective throughput several times over.
func (b *Batcher) Run(ctx context.Context) {
ticker := time.NewTicker(50 * time.Millisecond)
defer ticker.Stop()
batch := make([]Digest, 0, b.max)
for {
select {
case d := <-b.in:
batch = append(batch, d)
if len(batch) < b.max {
continue
}
case <-ticker.C:
if len(batch) == 0 {
continue
}
case <-ctx.Done():
return
}
b.flush(ctx, batch) // one HSM round trip for the whole batch
batch = batch[:0]
}
}Prioritise by dispatch slot, not arrival. This was the big one. Not every invoice is equally urgent. A parcel leaving the warehouse in twenty minutes needs its invoice now. One leaving tomorrow morning can wait. We changed the signing queue to order by dispatch slot.
On a sale night arrivals blow past signing capacity for a while. The question isn't how to avoid a backlog; it's who waits.
A backlog during a sale is not a failure. It's physics. What matters is that the backlog is made of documents that can afford to wait, and that the system knows which ones those are. Once the queue understood dispatch slots, a sale night went from "warehouses waiting on invoices" to "a queue that builds after midnight, drains in under an hour, and never holds up a truck".
Backpressure, end to end
Prioritisation only works if pressure flows backwards cleanly. A few things we learned the hard way:
- Bounded queues everywhere. An unbounded in-memory queue in front of the signer will happily absorb a sale night and then fall over. Every stage had a bounded queue and blocked or shed when full.
- Shed the right work. When the signer is saturated, rendering more PDFs only makes the pile bigger. Render workers watched the signing backlog and slowed down instead of racing ahead.
- Expose the backlog to operations. Warehouse teams could see "invoices pending for your next dispatch slot". When that number was zero, nobody called us.
Reconciliation is the safety net
Every stage was idempotent and every worker was careful. We still ran reconciliation every fifteen minutes, because the question an auditor asks isn't "is your code correct?" It's "show me".
The job compared four counts per series: shipments dispatched, invoices requested, invoices numbered, invoices signed and archived. It also listed every invoice that had been in an intermediate state for longer than ten minutes. Most days the list was a few dozen items from transient HSM timeouts, and the job simply re-drove them. Some days the list was long, and that was always the first sign of an incident — usually before any alert fired.
The most valuable thing reconciliation found was not a bug in our code. It was shipments the OMS had marked dispatched without ever telling us. A message lost upstream would otherwise have meant a parcel on a truck with no invoice. Reconciliation caught it within fifteen minutes, every time.
Audit and retention
Once signed, an invoice goes to storage that cannot be modified or deleted for the retention period. We kept three things together: the PDF, the structured data it was rendered from, and the signature. Any one of them alone is less useful than you'd think. Auditors want the document. Finance wants the data. Disputes want proof that neither changed.
We also logged every state transition for every invoice, with the worker that made it. That log was dull to build and was used constantly. "When was this invoice signed, by which key, and was it ever re-rendered?" became a lookup instead of an investigation.
What I'd do differently
Treat the series as the unit of scale from day one. We started with coarser series and split them under load. Splitting live series is delicate work you don't want to do in the middle of a sale season. Model the series the way the rules define them, from the start.
Build reconciliation before the pipeline is fast. It caught more real problems than any test, and it would have caught the early ones sooner.
Put the dispatch slot on the request. We added it later and retrofitted priority onto queues that had been FIFO for years. It should have been part of the contract with the OMS from the first event.
Golden files for every template. A small set of reference invoices rendered and compared on every change costs almost nothing and would have saved us the font incident and a couple of others like it.
What stayed with me
Most systems I've worked on since have had something like this underneath: a sequence of steps where each one must happen exactly once, in order, and survive any machine dying at any point. Agent tool calls with approvals look a lot like invoice states. Notification dispatch looks a lot like signing queues.
The pattern is always the same. Make every step idempotent. Store the state, not just the result. Put the slow, scarce resource last, and decide in advance who waits when it runs out. Then reconcile anyway, because the question will always be "show me".