Summary#
Razorpay is an Indian payments company. Merchants use it to accept cards, net banking, UPI (India's real-time bank-to-bank payment system) and wallets, and to move money out again through settlements, transfers and payouts. A single payment touches the merchant's checkout, Razorpay's services, one of several payment gateways or acquiring banks, a card network or the UPI switch, and finally the customer's bank. Razorpay controls only part of that chain.
That one fact shapes the whole engineering blog. Banks and gateways slow down and fail every day, often for minutes at a time, often without warning. So the posts keep returning to one question: how do you build a reliable product on top of unreliable partners? The answers are concrete: detect failures in seconds from success-rate signals, route around them automatically, protect your own databases from the slowness of others, make every write to money correct even under concurrency, and run incident response like a well-drilled team.
This page studies the Razorpay posts in eight families:
- When banks fail: why downtime is the normal case, detecting downtimes from success-rate signals with Apache Flink, and smart routing around failing gateways.
- Correctness in the money path: reliable dual writes with a transactional outbox, a deadlock that silently corrupted merchant balances, and leader election with Consul.
- Surviving the peak: IPL (the Indian Premier League cricket season) and flash-sale bursts, and performance testing before go-live.
- Notifications and integrations: a notification service under growing load, and replacing a cron job with real-time webhooks.
- The data platform: a real-time denormalised streaming platform in three parts, and analytics on Trino and Alluxio.
- Observability and incidents: trillions of metric points, the tracing journey, alerts as a service, the command center and a better 5-why root cause analysis (RCA).
- Product, experiments and security: high availability of the payments dashboard, the Splitz experimentation platform, and Istio for mutual TLS.
- Synthesis: what the posts teach together, and how they map onto classic interview problems.
Why It Exists#
Most payment system designs in textbooks and interviews focus on the inside of the system: an idempotent API, a ledger, a state machine, a queue for retries. Those matter, and the payment system case study covers them. Razorpay's posts are valuable because they focus on the parts that sit between systems, where the real trouble lives:
- Dependencies you do not control. A bank's API might have a latency agreement of up to 20 seconds. During a traffic spike, the IPL post reports bank response times reaching 20 times their normal P99. Your threads, connections and queues fill up waiting for someone else.
- Traffic that arrives in bursts. The IPL post defines burst traffic as about ten times the average transactions per second for the rest of the day, arriving in 10-minute windows before matches. Autoscaling takes 3 to 4 minutes to add nodes, which is longer than the burst takes to knock a system over.
- Money that must be exactly right. A single lost event can produce a wrong fee, balance or settlement. A race between two flows can overwrite a balance. These bugs do not crash anything. They quietly cost money.
- Many teams, one platform. Dozens of teams ship into shared systems such as the payments dashboard, alerting and the data lake. Ownership, guard rails and process matter as much as code.
The posts also document Razorpay's assumptions honestly, including the ones that turned out wrong: a downtime detector built inside the system it was meant to watch, Prometheus outgrowing a single node, a 5-why RCA format that explained why things broke but not why recovery was slow. That makes them a good source for the habit this handbook encourages: write down your assumptions about traffic, latency, consistency and maintenance, then look for what the design gave up.
How It Works#
The diagram shows where each family sits. A customer pays on a merchant's checkout. Requests pass rate limits at an Nginx sidecar, reach the payments API (historically PHP with Laravel, increasingly Go), and use MySQL through a ProxySQL sidecar. A routing layer picks a gateway using success-rate predictions, and a Flink-based downtime service watches every payment event. Outcomes flow back to merchants as webhooks, into the data lake as change events, and into metrics, traces and alerts.
The lessons follow the families in order. Each covers one post or a few linked posts, and ends with what Razorpay gave up.
Family 1: When banks fail
Lesson 1: Why bank downtime is the normal case#
Assumptions.
- Traffic: payments spread over many methods (cards, net banking, UPI, wallets), many banks and several gateways. Each combination has its own failure pattern.
- Latency: a payment involves the customer, the bank's pages or app, and network hops that Razorpay does not own. Bank APIs may take many seconds; the IPL post cites agreements of up to 20 seconds.
- Consistency: a payment's final status must be exact, but the information that "HDFC net banking is degraded right now" can be a few seconds stale.
- Maintenance: dozens of partner integrations, each changing on its own schedule, with no shared status page that is reliable.
Razorpay's own definition from the downtime post is broad on purpose: any outage or partial degradation in a payment system, bank or integration that could stop a customer from completing a transaction counts as a downtime. Note what that includes. It is not only "the bank is down". It is also "OTP pages are slow for one card issuer", "one gateway's UPI collect requests are timing out", or "a scheme's authorisation success rate has halved".
Why this is normal, not exceptional. Think of a payment as a relay race with five runners: the checkout, Razorpay, the gateway, the network or UPI switch, and the issuing bank. If each runner is available 99.9 percent of the time and failures are independent, the whole race completes only 0.999⁵ ≈ 99.5 percent of the time. That is about 3.6 hours of failure a month. Now multiply by hundreds of banks and issuers. At any given minute, something in the matrix of methods and banks is likely degraded. A payments company that treats downtime as a rare incident will be in permanent incident mode.
What it costs. The downtime post reports that, on average, more than 20,000 payments a month failed purely because customers picked a payment method that was unavailable at that moment. Each failure is a lost sale for a merchant and a frustrated customer. Worse, retries pile load onto the very bank that is struggling.
The three responses. Razorpay's posts describe three layers of defence, which the next two lessons cover in depth:
- Detect degradations fast, per cohort (method, bank, card type, merchant), from success-rate signals.
- Inform merchants and customers, for example by marking a bank as "facing issues" on checkout, so customers choose another method.
- Route automatically to the gateway most likely to succeed for this payment, and away from degraded ones.
Overlooked constraints.
- Pending is not failure. Many Indian payment methods can sit in a pending state, especially UPI and net banking. A naive success-rate calculation that counts pending as failed will raise false alarms.
- Your own retries are part of the load. When a bank is slow, client retries and duplicate submissions increase its load at the worst moment.
- The customer can often fix it. Unlike most system failures, a payment failure has a human workaround: pay another way. Information is a reliability tool.
What Razorpay sacrificed. Simplicity. Treating every bank as a partly unreliable dependency means building and running detection, routing and communication systems that a single-bank integration would never need.
Deep Dive: how much does one point of success rate matter?Show
Setup (handbook's illustration). A gateway processes 10 million payment attempts a day, with an average order value of 800 rupees and a success rate of 70 percent.
One point of success rate. Raising success from 70 to 71 percent adds 100,000 successful payments a day, worth 80 million rupees of merchant sales. Even if half of the failed customers would have retried successfully anyway, the gain is about 50,000 payments a day.
Downtime in the matrix. Suppose there are 300 issuer and method combinations, each degraded for 20 minutes a day on average, at random times. The expected number degraded at any minute is 300 × 20 / 1,440 ≈ 4.2. With a Poisson model, the chance that none is degraded at a given minute is e^(−4.2) ≈ 1.5 percent. So 98.5 percent of the time, at least one combination is degraded. That is what "downtime is the normal case" means in numbers.
Detection speed. If a degradation lasts 20 minutes and detection takes 10 minutes, half the damage has been done before anyone reacts. If detection takes 1 minute, 95 percent is avoidable. Mean time to detect (MTTD) is the main lever, which is why the next lesson is about detection.
Lesson 2: Detecting downtimes from success-rate signals (2021)#
Assumptions.
- Traffic: billions of payments, each producing about 15 workflow events (created, authorised, failed and so on), of which only 3 decide the final status.
- Latency: detection should take well under the 2 minutes of the first version, ideally seconds to a minute.
- Consistency: detection can be slightly stale, but it must not create false positives from database replication lag.
- Maintenance: many teams want their own rules on the same payment groups, such as SBI card payments or HDFC net banking, including experimental rules running beside production ones.
The quick fix and its four problems. The first version polled the database at regular intervals, computed the success rate (SR = successful payments ÷ total payments) for each group, and raised a downtime if it dropped below a threshold. It worked for simple cases but had four flaws that are common to any "monitor by polling the main database" design:
- Availability. It lived inside the main payment system. If payments were down, so was the detector. A monitor must not share fate with what it monitors.
- Detection time. To protect the database, it ran every 2 minutes. A downtime that started just after a run went unseen for nearly 2 minutes.
- Extensibility. It only worked at the Razorpay level, not for merchant-specific downtimes.
- Accuracy. It read from replicas, and replication lag produced false positives: payments that had succeeded on the primary still looked pending.
Requirements for the new system. Low MTTD; severity levels (high, medium, low); detection across dimensions such as method, issuer and card type; rules configurable by merchants and internal teams; several rules running in parallel on the same cohort; and automated accuracy checks to debug false positives and misses.
Two designs. A database-based design needed a new store, a write pipeline, a cron to compute SR, a purge job and the detection logic itself: many moving parts and the same replication and frequency problems. A stream-based design computes everything from the event stream. Razorpay chose streams and picked Apache Flink over Spark for its low latency, high throughput and libraries such as complex event processing (CEP), despite Flink being newer to the team. See Flink and batch and stream processing.
Job 1: payment status. The first Flink job consumes workflow events, filters out the 12 or so that do not matter at the source, and keys the stream by payment ID (like GROUP BY in SQL). Within each key, it works out the payment's status and emits a single status event to Kafka. The catch is scale: billions of payments create billions of short-lived keyed states. If you never clear them, heap memory grows until garbage collection stalls and the process dies. Flink's state TTL (time to live) clears expired keys automatically, for example once the status is known or after a few minutes. But TTL itself costs memory, because Flink stores a last-access timestamp with every entry.
Job 2: downtime detection. The second job groups status events into payment cohorts, computes SR over a window, compares it with thresholds, and repeats at intervals. The hard part is that "window" varies:
- Some rules want the last N payments (a count window), others the last N minutes (a time window).
- Thresholds vary by severity, method and merchant.
- Some methods, such as net banking, need several strategies at once to detect quickly.
The team tried two proofs of concept. The first connected two streams, payments and rules, but gave no control over how payments were aggregated. The second used Flink's built-in sliding time windows and count windows, but those are fixed at deployment, so changing a rule meant redeploying. The final design was a custom dynamic window built on Flink's timer service, using a known Flink pattern: broadcast the rules. Commands (a rule plus its aggregation settings) are broadcast to every parallel instance. A "dynamic keyed stream generator" connects payments with commands and emits a keyed stream for every cohort a command defines. The detection function then runs each command on its cohort.
Design details worth copying.
- Production, experimental and test rules run side by side on the same cohorts without affecting each other. That is how detection strategies improve safely.
- Downtimes are held in state and resolved only when SR rises back above the threshold, which avoids flapping.
- Custom state cleanup. In the detection job, Flink's built-in TTL used too much CPU, and payment lifetimes differ across cohorts, so the team wrote its own cleanup.
- A moratorium operator silences short SR fluctuations so that a 30-second blip does not raise a downtime.
Accuracy checks. A detector is only useful if people trust it. The team compared the SR the detector computed during each downtime with the actual SR of those payments, and with the SR trend for the same time in earlier periods. To do this, the detection function emits SR logs through a Flink side output (a secondary output stream) to the data lake, with start and end times, successes and failures. Weekly automated accuracy reports and these logs make false positives debuggable.
Testing streaming code. Flink's test harness tests individual operators with simulated watermarks and processing time. The team also built a small data flow per process function so a feature could be tested in isolation. For example, the moratorium only needs downtime events as input, not a full payment stream, which made edge cases easy to generate.
Results. The service detects downtimes on more than 50 payment cohorts at the Razorpay level and more than 200 merchant-specific cohorts. Next steps in the post were zero-downtime upgrades of the detector itself, canary releases, and a low-latency broadcast system for downtime notifications.
Overlooked constraints.
- Small cohorts are noisy. A cohort with 10 payments a minute has a huge SR variance. Count windows help small cohorts; time windows suit large ones.
- Status arrives late. UPI and net banking payments can stay pending for minutes. The detector must decide how to count pending, or wait.
- Detectors need their own observability. The SR logs and accuracy reports exist because a silent detector is worse than none.
What Razorpay sacrificed. Familiarity and simplicity. Flink was new to the team, custom windows are more complex than built-in ones, and two jobs plus Kafka plus a rules stream is more to run than a cron job. In exchange it got low MTTD, independence from the main database and rules that change without redeploying.
Deep Dive: the statistics of a success-rate thresholdShow
Why thresholds need a minimum sample. An SR estimate from n payments has standard error √(p(1 − p) / n). With true SR p = 0.8:
- n = 20: standard error ≈ 0.089. A healthy cohort will show SR below 0.65 about 5 percent of the time (z ≈ −1.68). A 60 percent threshold would fire falsely about 1 in 77 windows (z ≈ −2.24).
- n = 200: standard error ≈ 0.028. SR below 0.70 is now a 3.5-sigma event, about 1 in 4,000.
So the same threshold is too jumpy on small cohorts and fine on large ones. That is why rules carry a count, a threshold and a strategy per cohort.
Detection delay versus false alarms (handbook's illustration). HDFC net banking runs 600 payments a minute at SR 0.80 and suddenly drops to 0.40.
- Count window of 100: the window fills with post-drop payments in 10 seconds. After about 50 bad payments the window SR is about 0.6, so a 0.6 threshold fires after roughly 5 seconds.
- Time window of 5 minutes: SR falls linearly. It reaches 0.6 after 2.5 minutes.
The count window detects 30 times faster for this cohort, while a small cohort with 10 payments a minute needs 10 minutes to fill a count window of 100. Hence dynamic windows per rule.
Hysteresis. Opening a downtime at SR below 0.6 and closing it at SR above 0.7 avoids flapping when the true SR hovers near 0.6. The moratorium adds a time hysteresis: ignore dips shorter than, say, 60 seconds.
Related ideas. The same reasoning drives the SRE golden signals and burn-rate alerts, and the statistics are the same ones behind A/B tests in the experimentation platform.
Lesson 3: Smart routing around failing gateways (2020 to 2021)#
Assumptions.
- Traffic: during IPL bursts, payments jumped from about 200 to about 1,500 requests a second within seconds.
- Latency: the routing decision is on the payment's critical path and must take milliseconds.
- Consistency: a routing score can be a little stale; a payment's outcome cannot.
- Maintenance: routing rules were originally edited by hand, which does not scale when peaks change in seconds.
The problem. A merchant's payments can usually be sent through more than one gateway or acquiring bank. When one degrades, the IPL post explains, Razorpay already shifted transactions to others, but people changed the rules manually. At 200 requests a second that is slow; when load jumps sevenfold in seconds it is hopeless. Worse, sending traffic to a degraded gateway does not only fail those payments. Slow responses hold threads and database connections, so a degraded partner degrades Razorpay itself.
The solution. Over a few months after IPL 2019, Razorpay built a machine-learning routing system. It consumes payment success and failure events across many dimensions: card type (credit or debit), gateway, scheme (Visa, Mastercard, RuPay), the IIN (the first six digits of a card, which identify the issuer and product) and others. Models use real-time data to predict, for each payment, the probability of success at each gateway, and the payment goes to the best one. The post reports success rates improving by 60 percent during burst periods and 4 percent during normal traffic, and no manual intervention. The flash-sale summary from systemdesign.one describes the same idea: forward traffic only to gateways that are operational, using predicted success probabilities.
How it fits with detection. Lesson 2's downtime service and the router solve different halves of the problem. Downtimes are coarse, explicit states that humans and merchants can see ("ICICI cards: high severity"). Routing scores are continuous and per payment. A good router uses both: hard-exclude gateways under a declared downtime, then rank the rest by predicted success. This is the same pattern as Swiggy's payment routing, which uses explore-exploit to keep estimates fresh.
Overlooked constraints.
- Feedback loops starve estimates. If the router stops sending traffic to a gateway, it stops learning whether that gateway recovered. Some exploration is needed, as Swiggy's posts make explicit.
- Routing changes cost. Gateways charge different fees, and some merchants have contracts with specific acquirers. Pure success-rate routing can raise costs or break agreements.
- Correlated failures. If two gateways share a bank or network underneath, routing between them does not help. Diversity matters more than count.
What Razorpay sacrificed. Transparency and some control. Manual rules are easy to explain; model-driven routing needs monitoring, explanations for merchants and guard rails. It also needs real-time feature pipelines, which are another system to keep healthy.
Deep Dive: what a 60 percent success improvement during bursts impliesShow
Reading the number (handbook's illustration). "Improved success rates by 60 percent" during bursts most plausibly means relative improvement. If the burst SR was 50 percent with manual routing, it became 80 percent with ML routing. That is plausible when one large gateway degrades badly during a burst and manual routing reacts in minutes rather than seconds.
Why bursts amplify the gain. During a burst of 1,500 payments a second, a 3-minute delay in switching a degraded gateway that carries 40 percent of traffic affects 1,500 × 0.4 × 180 = 108,000 payments. If that gateway's SR drops to 20 percent, about 65,000 extra payments fail before a human reacts. Automatic routing that reacts in 10 seconds reduces that to about 3,600.
Why normal-time gains are smaller. In steady state, gateways are mostly healthy and differences between them are a few points. A 4 percent relative gain on a 70 percent SR is about 2.8 points, which is still large in money terms (see Lesson 1).
The exploration cost. If 5 percent of traffic is routed for exploration and the explored gateway is 10 points worse on average, the cost is 0.5 points of SR. That is why exploration rates are kept small and why adaptive methods such as Thompson sampling are attractive at high volume.
Family 2: Correctness in the money path
Lesson 4: Reliable dual writes with a transactional outbox#
Assumptions.
- Traffic: moderate. The first user was credcase, Razorpay's credential-management service, writing auth credentials to its own database and to other services.
- Latency: the second write may happen a little later, but the caller should see its own write at once (read-your-writes).
- Consistency: both writes must eventually happen, or the system is in a broken state.
- Maintenance: many Go services need the same guarantee, so it should be a library, not copied code.
The problem. A dual write is when one operation must update two systems, such as your database and another service, a cache or a message broker. The outbox post uses a hotel booking example. The booking service saves a booking in its database and then calls the inventory service to reduce the count of free rooms. If the call fails after the save, you have a booking with no reserved room. If you call first and the save fails, you have a reserved room with no booking. A distributed transaction across both services would fix this, but it is heavy, couples the services tightly and is often not supported (see distributed transactions).
The pattern. The transactional outbox turns two writes into one. In the same local database transaction that saves the booking, insert a row into an outbox table that describes the work still to do ("call inventory to reserve room 204 for these dates"). In a NoSQL store that only supports single-document transactions, the outbox can be an attribute of the document itself. A separate processor reads pending outbox rows and executes them, retrying until they succeed. Because the main write and the outbox row commit or roll back together, either both exist or neither does. The caller's own data is visible immediately; the side effect happens a moment later.
A real-world analogy: a restaurant waiter does not run to the kitchen and the bar at the same moment. They write the full order on one ticket, which goes on the spike. The kitchen and bar each pick up their part from the ticket. If the bar is busy, the drink is late but not lost.
Razorpay's choices. Many outbox implementations publish events to a broker such as Kafka, and the change data capture approach tails the outbox table from the database log. For credcase, Razorpay chose a simpler design without a broker. The outbox stores generic tasks, such as an HTTP call to another service, and the processor runs them directly. Because a task can run more than once (the processor might crash after the call but before marking it done), every task must be idempotent: running it twice has the same effect as once. See idempotency.
Outboxer, the Go library. The team packaged the pattern as a library called Outboxer:
- Job handlers. You implement a handler interface for each kind of task and register it with a name. You then call a send method inside an active database transaction (the post uses the GORM ORM), passing the handler name and payload.
- Workers. On start, Outboxer runs a pool of fetcher goroutines that read pending jobs and a pool of processor goroutines that execute them, with exponential backoff between retries.
- A store interface, with a MySQL implementation first and Postgres and Oracle planned.
- An encoder that serialises the payload (Go's gob encoding, then Base64).
- A job record that holds the status, handler name, serialised payload, next attempt time and number of attempts.
- Configuration for the wait after an empty read, the maximum attempts and the backoff policy. It also takes a logger and a Prometheus registry for metrics.
The post notes that the library does not guarantee order: two jobs created in sequence might execute in a different order.
A minimal processor loop (handbook's illustration, pseudo-code):
// Runs in each fetcher; processors execute jobs from the channel.
while (running) {
const jobs = store.fetchDue(batchSize); // status = pending AND next_attempt_at <= now
if (jobs.length === 0) { sleep(waitAfterEmptyReadMs); continue; }
for (const job of jobs) {
const handler = handlers[job.handlerName];
try {
handler.execute(decode(job.handlerSerialized)); // must be idempotent
store.markDone(job.id);
} catch (e) {
job.numAttempts += 1;
if (job.numAttempts >= maxAttempts) store.markFailed(job.id); // alert on this
else store.reschedule(job.id, now() + backoff(job.numAttempts));
}
}
}Overlooked constraints.
- Two fetchers can pick the same job. Without row locking (for example, SELECT ... FOR UPDATE SKIP LOCKED) or a claim step, the same job runs twice concurrently. Idempotency covers correctness; claiming saves wasted work.
- The outbox table grows. Done jobs must be purged or archived, or fetch queries slow down. This is the same problem as any queue on a relational table.
- Failed jobs need a human. After the maximum attempts, a job is a stuck business operation. It needs alerting and a way to replay it.
What Razorpay sacrificed. Immediacy and ordering. The second write happens after a delay (the fetch interval plus processing), and jobs can run out of order. Using the database as the queue also adds write load to the primary database. In exchange it got atomicity without a broker or distributed transactions.
Deep Dive: outbox, CDC or two-phase commitShow
Three ways to make two writes agree.
| Approach | How it works | Latency | Ordering | Operational cost |
|---|---|---|---|---|
| Two-phase commit | A coordinator asks both systems to prepare, then commit | Synchronous, slowest | Strong | Needs XA support everywhere; a blocked coordinator blocks everyone |
| Outbox with polling | Insert task in the same transaction; poll and execute | Poll interval plus work, often 100 ms to seconds | Not guaranteed unless per-key serial | Low: just a table and workers |
| Outbox with CDC | Insert event in the same transaction; a log tailer such as Debezium publishes it to Kafka | Tens to hundreds of ms | Per key, via Kafka partitions | Needs CDC and a broker |
Polling cost (handbook's illustration). Ten processes each polling every 200 ms run 50 queries a second against the primary even when idle. An index on (status, next_attempt_at) keeps each poll a cheap range scan. Outboxer's "wait after empty read" setting is exactly this trade-off: a longer wait cuts idle load but adds latency.
When ordering matters. If credential updates for the same merchant must apply in order, process jobs per merchant serially. You can add a sequence number per key and have the consumer reject older versions, or partition jobs by key across processors.
Exactly-once is an illusion here. The processor can always crash between "call succeeded" and "mark done". Delivery is at least once; the effect is exactly once only if the target is idempotent, typically via an idempotency key derived from the outbox job ID. See delivery semantics.
Lesson 5: Solving deadlocks that corrupted balances#
Assumptions.
- Traffic: a merchant's balance changes with every payment (credit), refund, transfer and settlement. Busy merchants have several balance changes a second.
- Latency: balance updates are on the payment path and must be fast.
- Consistency: absolute. A balance must always equal the sum of its transactions.
- Maintenance: a large PHP monolith accessing MySQL through PDO, Laravel's database layer.
The symptoms. Two alarms raised the investigation: some merchant settlements were skipped, and the transfer flow sometimes threw a "negative balance" error. Razorpay keeps one balance row per merchant and a transaction table that records each credit or debit with the balance after it. Comparing the ideal balance (sum of transactions) with the actual one in a spreadsheet showed the classic sign of a lost update: two transactions had read the same starting balance, and one update overwrote the other. It only affected merchants who used both credits and transfers, and only when a payment and a transfer happened at the same millisecond.
The puzzle. The code already did the right thing on paper: inside a database transaction, it read the balance with SELECT ... FOR UPDATE, which takes an exclusive row lock so no other transaction can read-for-update or change the row until commit. So how could two threads read the same balance?
The investigation. This is a model debugging story:
- Reproduce. The team wrote a Java and TestNG test that fired payments and transfers at the same merchant on staging. At first nothing happened. They removed calls that slowed the flow and created a fresh merchant per run so old data did not interfere, and then the bug reproduced.
- Look in the database. The slow query log showed nothing. MySQL's performance_schema showed two threads reading the same balance. The general query log on staging showed the same rows locked by two threads at the same time, which should be impossible with FOR UPDATE inside a transaction.
- Experiment. Switching the isolation level to SERIALIZABLE fixed the bug but cut throughput by about 70 percent. Setting PDO's ATTR_EMULATE_PREPARES to true changed how statements were sent and, crucially, made deadlock errors appear in the logs. That was the clue.
The root cause. Two flows took the same two locks in opposite order. The payment flow locked the credits row and then the balance row. The transfer flow locked balance and then credits. When both ran at once, each held one lock and waited for the other: a deadlock. InnoDB, MySQL's storage engine, detects deadlocks and kills one transaction, rolling it back and releasing its locks.
That alone would be safe: the application would get error 1213 and retry. But a PHP bug (#76742 in the PHP bug tracker) meant that, with mysqlnd and ATTR_EMULATE_PREPARES set to false, PDO ignored the deadlock error. The application did not know its transaction had been rolled back. It carried on running statements, which now executed in autocommit mode, one by one. In autocommit, SELECT ... FOR UPDATE outside a transaction gives up its lock as soon as the statement ends, so it behaves like a plain SELECT. The thread read a balance without any lock, computed a new value, and wrote it, overwriting the other transaction's update.
The fix. Make every flow take locks in the same order. The team swapped the order in the transfer flow so that it, too, locked credits before balance. With a consistent order, a cycle of waits cannot form, so this pair of flows cannot deadlock. The change was rolled out gradually using Splitz, Razorpay's experimentation platform (Lesson 20), so any regression would hit a small share of merchants first.
The safety net. The team also added an automated daily reconciliation: for each merchant, the sum of the day's transactions must equal the difference between the closing and opening balance. Any mismatch raises an alert. This is a direct check of the invariant, independent of the code that maintains it.
Lessons from the post. Good concurrency tests need fresh data, no artificial bottlenecks and an environment like production. Important entities such as balances should be versioned or audited so you can see how they changed. And the broader lesson: never trust that a lock was held. Check error codes, fail loudly, and reconcile.
Overlooked constraints.
- Drivers lie. The bug was in a database driver, not in Razorpay's SQL. Correct SQL is not enough; the whole client stack must surface errors.
- Deadlocks are expected. InnoDB will always kill some transactions under contention. Code must retry the whole transaction, not continue.
- Hot rows limit throughput. One balance row per merchant serialises all updates for that merchant. For very busy merchants this caps throughput regardless of locking order.
What Razorpay sacrificed. Some flexibility in code structure: every developer touching these tables must follow the lock-order rule. The daily reconciliation also adds batch load and a delay: corruption is caught within a day, not instantly. The SERIALIZABLE option was rejected because its 70 percent throughput cost was far too high.
Deep Dive: lock ordering, hot rows and alternativesShow
Why ordering prevents deadlock. A deadlock needs a cycle in the wait-for graph: A waits for B, B waits for A. If every transaction acquires locks in one global order (say credits before balance, and lower IDs before higher IDs), any waiting transaction waits only for a lock later in the order than the ones it holds. A cycle would require some transaction to wait for a lock earlier in the order, which never happens. This is the classic resource-ordering argument from operating systems.
Lost update in numbers (handbook's illustration). A balance of 1,000 rupees. A payment credits 500 and a transfer debits 300. The correct result is 1,200. If both read 1,000, the payment writes 1,500 and the transfer writes 700. Whichever commits last wins, so the balance is 700 or 1,500, wrong by 500 or 300.
Alternatives to row locks.
- Atomic update: UPDATE balance SET amount = amount + 500 WHERE merchant_id = ? AND amount + 500 >= 0. No read-modify-write in the application, so no lost update, and the check prevents negatives.
- Optimistic concurrency: keep a version column; UPDATE ... WHERE version = v; retry if zero rows changed. Good when contention is low.
- Append-only ledger: never update a balance in place. Insert ledger entries and derive the balance, caching it with a version. This is how double-entry ledgers in Stripe's and other payment systems are often built.
- Sharded counters: for very hot merchants, split the balance into N sub-rows and sum them on read.
See concurrency control and locking and ACID and isolation levels for the theory.
Why SERIALIZABLE was slow. In InnoDB, SERIALIZABLE turns plain SELECTs into locking reads (shared locks). Readers block writers on every row they touch, so concurrency collapses on hot rows. A 70 percent drop is consistent with that.
Lesson 6: Leader election with Consul#
Assumptions.
- Traffic: low for the election itself; the elected leader does periodic scheduling work.
- Latency: failover in seconds is acceptable.
- Consistency: at most one leader at a time is required, or two leaders would assign the same work twice.
- Maintenance: reuse infrastructure the team already runs.
The context. Metro is Razorpay's open-source asynchronous messaging system, a pub/sub layer. Its push mode delivers messages to subscriber endpoints using a pool of push workers. Something must decide which worker handles which subscription and rebalance when workers join or leave. That is a classic leader's job, like the Kubernetes scheduler assigning pods to nodes. If every node did it, they would conflict; if one fixed node did it, it would be a single point of failure. So the nodes elect a leader.
Why a lock service. Leader election is usually built on a distributed lock: whoever holds the lock is the leader. A correct lock needs strong consistency, which means a consensus protocol such as Paxos or Raft. Writing one yourself is hard and risky, so teams use ZooKeeper, etcd or Consul. Consul was already Razorpay's service registry, so they used its sessions and key-value (KV) store. See leader election and coordination and ZooKeeper and etcd.
What the lock must guarantee. Mutual exclusion (only one holder); freedom from deadlock (if the holder dies, the lock is eventually released, which Consul does with a session TTL); and fault tolerance (as long as a majority of Consul servers is up, the lock works, so Consul runs as a highly available cluster).
The four steps.
- Create a session with a TTL (time to live). If the session is not renewed in time, Consul invalidates it and releases its locks. A long TTL means slow failover when a node dies; a short TTL means more renewal traffic and more risk of losing leadership during a brief pause. Consul's lock delay stops anyone from taking a released lock for a short period, giving the old leader time to notice and stop work.
- Renew the session periodically. In the Go client this is a blocking renew call, so it runs in its own goroutine.
- Acquire the lock by writing an agreed key, such as a Metro leader key, with the session attached. The write succeeds only if no other session holds it. The value can carry the leader's ID so others know who leads.
- Watch the key. All nodes, including the leader, watch it. When it changes (released or expired), they try to acquire it again.
Edge cases. On a planned deploy, the leader steps down by releasing the lock or destroying its session, so another node takes over at once. On a crash, nothing releases the lock, so the others wait until the TTL expires.
Overlooked constraints.
- A lease is not a fence. A leader paused by garbage collection for longer than the TTL may wake up still believing it leads, while another node has taken over. The fix is a fencing token, a number that increases with each election (Consul's lock index can serve), which workers check before accepting commands. See distributed locking.
- Consul's health is now Metro's health. If the Consul cluster loses quorum, no one can be elected; an existing leader should keep working but cannot renew.
- Work must be resumable. A new leader must rebuild assignments from state, not from the old leader's memory.
What Razorpay sacrificed. Failover speed on crashes (up to a TTL plus lock delay) in exchange for safety, and a dependency on Consul in exchange for not building consensus themselves.
Deep Dive: choosing the TTLShow
The trade-off (handbook's illustration). With N nodes renewing every TTL/3:
- TTL 10 s: renewals every 3.3 s. With 50 nodes, that is 15 writes a second to Consul, which is fine. Crash failover takes up to 10 s plus the lock delay (Consul's default is 15 s), so up to 25 s.
- TTL 60 s: renewals every 20 s, 2.5 writes a second. Failover takes up to 75 s.
For assigning subscriptions to push workers, 25 seconds of no rebalancing is harmless, because existing assignments keep delivering. That is why leader-based schedulers tolerate slow failover.
Why lock delay exists. Suppose the leader's network partitions from Consul for 12 s with a 10 s TTL. Consul releases the lock, but the old leader does not know yet. Lock delay keeps the lock unavailable for a period so the old leader's own renew failure tells it to stop before the new leader starts. It narrows, but cannot close, the window where two leaders act. Only fencing closes it.
Raft underneath. Consul servers replicate the KV store with Raft. A lock write commits when a majority acknowledges it. With 3 servers, one can fail; with 5, two can fail. See consensus.
Family 3: Surviving the peak
Lesson 7: Flash sales and IPL peak traffic (2019 to 2020)#
Assumptions.
- Traffic: bursts of about ten times the day's average transactions per second (Razorpay's own definition), lasting about 10 minutes, starting around 30 minutes before each IPL match. Food delivery and fantasy gaming merchants drive them. Load can jump from about 200 to 1,500 requests a second within seconds.
- Latency: Razorpay's own work is fast, but each payment waits on a bank whose agreed response time can be up to 20 seconds and whose P99 can spike to 20 times normal during bursts.
- Consistency: payment state must be exact even when the system is overloaded. Shedding load is acceptable; corrupting state is not.
- Maintenance: a PHP and Laravel monolith on Kubernetes, partway through a move to Go.
Background. The IPL post sets the scene: by 2018, about a quarter of India's transactions were electronic, pushed by UPI. IPL matches last about four hours and the season runs for weeks, so the same burst happens every evening. In IPL 2019, Razorpay had downtimes on three consecutive days, and some high-traffic customers had to be rate-limited. The post lists what went wrong:
- Alerting: alerts came late, and it was hard to correlate problems across services.
- No throttling: nothing stopped one merchant's burst from overwhelming shared systems, so the platform was effectively open to denial of service.
- Dependencies: slow bank responses created back pressure. Threads and connections stayed blocked waiting on gateways.
- Manual routing: shifting traffic away from bad gateways needed humans (Lesson 3).
- Database connections: PHP has no built-in connection pooling, and Laravel held a MySQL connection for the whole request. A request that waited 20 to 30 seconds on a gateway held a database connection doing nothing. Under a burst, MySQL ran out of connections.
The post describes how the team prepared for IPL 2020 in four streams: application, infrastructure, monitoring and performance testing.
Fix 1: connection pooling with ProxySQL. ProxySQL is a MySQL-aware proxy. The application connects to ProxySQL, which keeps a smaller pool of real connections to MySQL and multiplexes many client connections over them, handing a backend connection to a client only while a query runs. Benefits listed in the post: idle connections no longer pin MySQL connections; prepared statements are cached; and there are far fewer TLS handshakes and connect calls to MySQL.
The interesting choice is where to run it. There were three options: a central ProxySQL service, a DaemonSet (one per Kubernetes node), or a sidecar in every application pod. Razorpay chose the sidecar. It keeps the blast radius small (one bad proxy affects one pod), the application talks to it over a UNIX socket with no network hop, and there is no TLS between app and proxy. The costs: Kubernetes shutdown signals (SIGTERM) had to be ordered so the proxy outlived the app's last query, and deploys became slower.
The team learned several details the hard way:
- ProxySQL cannot share a backend connection while a transaction is open on it, so long transactions still pin connections.
- They rolled out gradually, with an application-level fallback: on certain ProxySQL errors, and only when no transaction is active, the app connects to MySQL directly.
- Schema changes with ALTER had to bypass ProxySQL, which they controlled through a Kubernetes ConfigMap flag. The post lists this as still open.
Fix 2: rate limiting at the edge of each pod. The old limiter was a leaky bucket inside the application. It shared a Redis instance with the application and needed several Redis calls per check. Under load, the limiter added latency and competed with the app for Redis. The new design is an Nginx sidecar proxy with its own dedicated cache and a fixed-window algorithm: one atomic counter per key per window, with a TTL. Requests over the limit are rejected before they reach PHP. A fixed window can allow up to twice the limit across a window boundary, but with one-second windows the team judged that acceptable. Limits are applied per route per merchant, per merchant overall, and per route across all merchants. See rate limiting and the rate limiter case study.
Fix 3: smart routing. Covered in Lesson 3.
Fix 4: observability. Metrics moved to VictoriaMetrics with Grafana dashboards and alerts on both business KPIs (payment success rates) and engineering KPIs, each with a runbook. Lesson 15 tells that story.
Fix 5: infrastructure. Cluster autoscaling and Horizontal Pod Autoscaler (HPA) settings were tuned, images were pre-warmed so new pods start faster, deploys were sped up, disaster-recovery clusters were added, and the container network (CNI) was reworked. Because adding nodes takes 3 to 4 minutes, longer than a burst takes to hurt, the team automated a pre-scale-up: before each match, capacity is raised to the expected peak plus a margin (the post describes x plus 100 TPS) and scaled down afterwards.
Fix 6: code. Query and code optimisations, and moving synchronous work to asynchronous paths where the customer did not need to wait for it.
Result. The post reports that IPL 2020 ran for 45 days with no degradation or downtime.
An external view. A systemdesign.one newsletter on Razorpay's flash-sale handling (May 2024, Neo Kim) summarises the same IPL 2020 story: 23 million or more fans and flash-sale peaks of about 1,500 requests a second. The newsletter says it is based on public research and may differ from the real implementation, so treat its extra detail as a reasonable reading rather than fact. It adds a few framings:
- Thundering herd. Many clients retrying at once after a failure can knock a recovering system over again. The defences are throttling at the server, exponential backoff with jitter on clients, caching, and ProxySQL rules that throttle expensive query patterns from heavy tenants.
- Cold capacity. New servers took about four minutes to become healthy, so capacity must be added before the burst. Baked machine images and pre-warming shorten that time; capacity planning decides how much to add.
- Load testing with k6 before the season, and a profiling loop: test, profile, fix, repeat.
- Separating payments and orders into separate services so one can scale and fail independently.
Overlooked constraints.
- Connection count is a hard limit. MySQL's max connections is a cliff, not a slope. Without a pool, connections needed = pods × workers per pod, regardless of how much work is done.
- Rate limits need fair defaults. A global limit protects the platform but can punish well-behaved merchants during another merchant's burst. Hence limits per merchant and per route.
- Pre-scaling needs a calendar. It works because IPL match times are public. Unscheduled spikes, such as a viral sale, still need headroom and fast scaling.
What Razorpay sacrificed. Burst precision (fixed windows over sliding ones), deploy speed and operational simplicity (a sidecar per pod), and cost (capacity held above need around every match). It also accepted rejecting some legitimate requests during spikes instead of risking everyone.
Deep Dive: the arithmetic of connection exhaustionShow
Without pooling (handbook's illustration). 100 pods × 20 PHP workers = 2,000 possible concurrent requests. Each holds a MySQL connection for its whole life. At 1,500 payments a second with a mean request time of 1 second, Little's law (concurrency = arrival rate × time in system) gives 1,500 concurrent requests. If gateway latency jumps to 10 seconds, concurrency becomes 15,000, far more than the 2,000 workers, and every worker holds a connection. MySQL with max connections at 3,000 would be close to its limit even before the spike.
With pooling. Suppose each request spends only 20 ms in queries. Database concurrency is then 1,500 × 0.02 = 30 connections, regardless of gateway latency. A pool of 200 backend connections has huge headroom. The gateway wait no longer touches MySQL. This is the same principle as bulkheads: isolate a slow dependency so its slowness cannot exhaust a shared resource.
Why workers still run out. Pooling saves the database, but PHP workers are still blocked for the gateway call. With 10-second gateways, 1,500 payments a second needs 15,000 workers. That is why the team also moved work to async paths and to Go, where thousands of goroutines can wait cheaply.
Fixed window boundary. With a limit of 100 per second, a client can send 100 at 0.999 s and 100 at 1.001 s: 200 in 2 ms. A sliding window or token bucket would prevent that. For a payments API protecting MySQL, a one-off 2x spike lasting milliseconds is absorbed by the pool, which is why the team accepted it.
Lesson 8: Performance testing before go-live (2022)#
Assumptions.
- Traffic: a new card tokenisation service for card issuers had a target throughput; the flow needs four API calls per transaction, so requests per second = 4 × target TPS.
- Latency: one call starts a workflow that completes through a callback, which can take up to 10 seconds.
- Consistency: each tokenisation must complete exactly once.
- Maintenance: a Java service with Hibernate, on Kubernetes, calling other internal services and external networks.
Why test before launch. The performance-testing post covers a service built for issuer tokenisation, which India's central bank (RBI) rules made mandatory: card numbers are replaced with tokens. The service had to hit its target on day one. The team's toolkit was k6 for load generation, Prometheus and Grafana for metrics, a mock service to stand in for third parties that cannot be load-tested, and real integrations for TCP connections and callbacks where mocks would hide the real behaviour.
The baseline was bad. Five pods with 5 GiB memory and half a CPU each crashed under load. The best sustained run reached only 20 percent of the target for 60 seconds.
Divide and conquer. Instead of tuning everything at once, the team load-tested each of the four APIs on its own. One, the API that starts the workflow, was the bottleneck. Then they fixed things one at a time:
- Memory. Dashboards showed 3 GB in use at idle, which looked like a leak. But the JVM's own metric showed only 0.5 to 1 GB used; the dashboard query was summing a cumulative series wrongly. Lesson: verify the metric before you trust it.
- Threads. VisualVM, a JVM profiler, showed time spent in log-masking filters (which hide card numbers in logs), in pool management, and in an unbounded number of async threads. A bounded thread-pool executor fixed the last.
- Scaling up did not help. Four 16-core nodes still topped out at 40 percent of target. More hardware was not the answer.
- Database. The schema had a redundant unique key on every primary key, unnecessary foreign keys, and an outer join that could be an inner join (the team overrode Hibernate's generated query). Adding caching and removing needless updates took database CPU from over 80 percent to 10 to 15 percent.
- An internal denial of service. A downstream service used Spring's RestTemplate with no timeout and three retries with no wait. Every slow callback became three callbacks, so total load was six times the transaction rate instead of four. Timeouts and backoff fixed it; a Hibernate Micrometer plugin exposed query latency so the team could see it.
- CPU metrics lied too. Grafana's CPU panel disagreed with AWS and kubectl top. Again: verify.
- The real culprit. A thread waited for a value from ZooKeeper with a busy wait: a loop that checked a map over and over until the value appeared or 8 seconds passed. Each waiting request burned a full CPU core doing nothing. Adding a short sleep between checks fixed it.
Results. After the fixes, one pod reached 24 percent of target and two reached 40 percent, using 4-core nodes with at most 2.8 cores busy. Seven pods reached 140 percent, and the fully provisioned infrastructure reached 180 percent: about an eightfold improvement overall.
The three lessons the team drew. Seeing is not believing, so verify metrics from a second source. Remove black boxes by profiling, tracing and exposing internals. Divide and conquer by testing components on their own before testing the whole.
Overlooked constraints.
- Mocks hide latency shapes. A mock that answers in 5 ms makes a pool look fine that would block for 10 seconds in production. The team used real integrations where timing mattered.
- Retries multiply load. Any client that retries without backoff turns a slowdown into an overload. Always budget retries in capacity planning.
- Dashboards are code. A wrong PromQL query sent the team chasing a leak that did not exist.
What Razorpay sacrificed. Time to launch: weeks of testing and profiling before go-live. It also needed a realistic test environment and mock services, which cost money and upkeep. The return was a launch without surprises.
Deep Dive: why a busy wait caps throughputShow
The cost (handbook's illustration). A busy-waiting thread uses one core for the whole wait. If each request waits on average 2 seconds for its ZooKeeper value, and a pod has 4 cores, the pod can run at most 4 waits at once: 2 requests a second, no matter how fast the rest of the code is. With a poll delay of 50 ms, each wait costs about 40 checks of a few microseconds, so CPU per wait drops by over 99 percent and the limit moves to thread count or memory.
Better than polling. A ZooKeeper watch or a future that completes on a callback avoids polling entirely: the waiting thread parks and is woken when the value arrives. Polling with a delay is the simple fix; event-driven waiting is the robust one.
Retry amplification. With r retries and no backoff, a failing call is attempted r + 1 times. If 30 percent of calls time out during a slowdown, expected attempts per call are 1 + 0.3 + 0.09 + 0.027 = 1.42 with 3 retries. If every call times out (the dependency is overloaded), attempts are 4 per call: exactly the 3x multiplication the team saw. That is why AWS's guidance on retries with backoff and jitter matters, and why token-bucket retry budgets cap retries at a fraction of traffic.
Capacity planning link. Load testing finds the knee of the latency curve. The capacity planning page explains how to turn a measured per-pod limit into a provisioning plan with headroom.
Family 4: Notifications and integrations
Lesson 9: Notification service under growing load (2022)#
Assumptions.
- Traffic: a typical peak of about 1,000 webhook and notification events a second, with spikes at quarter ends, festivals, flagship sales, the cricket World Cup and IPL.
- Latency: merchants expect webhooks within seconds; agreed delivery times depend on how fast each merchant's own server responds.
- Consistency: every event must be delivered at least once and recorded for audit.
- Maintenance: one shared service for SMS, email and webhooks across all of Razorpay's products.
What it does. When something happens to a payment, such as an order being paid, Razorpay notifies the merchant. Webhooks are the main channel: an HTTP POST to a URL the merchant registered, with an event like order.paid. The notification post focuses on webhooks because they carry the most volume and the strictest expectations. See the notification system case study.
The original design. API pods accepted notification requests and put them on an SQS queue (Amazon's managed queue). Worker pods consumed the queue, called the merchant's endpoint, and wrote the result to a database and to the data lake. A scheduler re-queued failed deliveries for retry. The system could handle about 2,000 transactions a second, but as load approached that, P99 latency rose from about 2 seconds to about 4.
What broke as it grew.
- Database reads slowed as tables grew, and the read replica hit its own peaks.
- Workers could not scale past the database's IOPS limit (input and output operations per second). Every delivery wrote to the database, so more workers simply meant more database pressure. The team scaled the database vertically from a 2xlarge to 4xlarge to 8xlarge instance, which does not go on forever.
- Delivery depends on customers. A merchant whose server takes 10 seconds to respond holds a worker for 10 seconds. A few slow merchants can starve everyone else.
- Unpredictable peaks. Business events like a big sale or a match create spikes that are hard to forecast.
The fixes.
- Priority queues. Instead of one queue, three: P0 for critical events, served by an exclusive worker pool; P1, the default; and P2 for bursty, less urgent traffic. A flood of P2 events can no longer delay a P0 payment notification.
- Rate limits per event type. Each event type gets a limit on its queue, such as X a second on P0 and Y on P1. Excess events go to a separate rate-limit queue that drains at a controlled pace. This also protects against a single product or tenant flooding the service, a form of denial-of-service protection and fair multi-tenancy.
- Decouple database writes with Kinesis. Workers no longer write to the database directly. They publish delivery results to Amazon Kinesis (a managed stream), and a separate consumer writes to the database at a throttled rate. Messages are idempotent so replays are safe. This also separated data-lake and audit writes and the retry flow from the main path. Worker scaling is now limited by the network, not database IOPS.
- Quality of service per customer. If a merchant's endpoint becomes slow, for example responses taking more than a few minutes in aggregate, the service lowers that merchant's priority for a few minutes, then checks again. The merchant is alerted so they can fix their endpoint. One slow customer no longer slows everyone.
- Observability. Grafana alerts on rogue events, rate-limited events, slow customers and webhook success rate; log dashboards; and tracing across the pipeline.
The post's summary lesson: when a system grows, shrink the problem. Split by priority, isolate slow customers, and take writes off the hot path, so each piece is small enough to reason about.
Overlooked constraints.
- Vertical scaling hides the real limit. Each upgrade bought months, but the design coupled delivery throughput to database IOPS. Decoupling was the real fix.
- The customer is part of your latency. Delivery time includes the merchant's response time. Per-customer isolation is needed whenever you call customer-controlled endpoints.
- Rate-limit queues need visibility. Events parked in a rate-limit queue are delayed; merchants and dashboards must see that, or it looks like loss.
What Razorpay sacrificed. Strict ordering and immediacy for low-priority events; P2 and rate-limited events may wait. Database records lag slightly behind deliveries because writes go through Kinesis. It also added a second streaming system to operate.
Deep Dive: sizing webhook workers and isolating slow merchantsShow
Little's law again (handbook's illustration). At 1,000 deliveries a second with a mean merchant response of 300 ms, you need 300 concurrent requests in flight. If 2 percent of merchants slow to 10 s, those 20 deliveries a second need 200 concurrent slots: two-thirds as many as everyone else combined. Without isolation, a few slow endpoints consume a large share of the worker pool.
Isolation options.
- Per-merchant concurrency caps: at most k in-flight requests per merchant. Simple and effective.
- Demotion (Razorpay's choice): move slow merchants to a lower-priority lane for a while.
- Separate pools per tier: large merchants get dedicated pools.
- Short timeouts with retries: cut each call at, say, 5 s, and retry later with backoff. This bounds slot time but increases total attempts.
Retry schedule. A typical webhook retry policy uses exponential backoff over hours, such as 1 min, 5 min, 30 min, 2 h and 6 h, then gives up and marks the endpoint as failing. Merchants must treat webhooks as at least once and deduplicate by event ID, the same contract described for Stripe webhooks.
Why Kinesis reduces IOPS. If 1,000 deliveries a second each write one row, that is 1,000 writes a second. A consumer can batch 500 records per insert, turning them into 2 insert statements a second, with throttling during peaks. The database sees smooth, batched load instead of spiky row-by-row writes.
Lesson 10: Real-time webhooks instead of polling (2025)#
Assumptions.
- Traffic: support tickets in Freshdesk (a third-party helpdesk), with assignment changes Razorpay needs to mirror in its internal case-management tool.
- Latency: agents and dashboards should see assignment changes in seconds, not minutes.
- Consistency: eventual, but no updates may be lost.
- Maintenance: Freshdesk has API rate limits and its own release cycle; Razorpay cannot change it.
The old design. A cron job ran every 15 minutes and pulled the last four days of ticket data from Freshdesk's API to catch changes. It used about 3,000 API calls an hour, close to the rate limit. It caused CPU spikes every 15 minutes, missed any update older than four days, showed data up to 15 minutes stale, and could not grow with case volume.
Three options considered.
- Batch fetching: fewer, larger API calls. Still not real time, with big payloads and timeouts.
- Freshdesk automation rules that call webhooks: real time, but every existing automation rule needed editing, changes made by the system itself (not by a rule) did not fire, and maintaining the rules is an ongoing burden.
- A custom Freshdesk app: a small serverless Node.js app that runs inside Freshdesk and reacts to the ticket-update event. On every assignment change, it sends a webhook to Razorpay. Chosen.
The design. Webhooks arrive at a gateway that authenticates them and applies rate limits. The payload is minimal: the ticket ID, the new assignee and a timestamp. Razorpay's service applies the update. Because webhooks can still be lost (timeouts, deploys, bugs), a reconciliation cron runs every 3 hours, using about 6,000 API calls a day, to catch anything missed. Push for speed, pull for safety.
Rollout. Grafana and Prometheus monitoring first. Then unit, integration and load tests. Then shadow mode: the webhook path ran in parallel with the old cron, and results were compared. Finally production, with the reconciliation cron and comparison counts as ongoing checks. Shadow mode found two issues: silent timeouts from the app (fixed with retries inside the app) and null assignments when a ticket was unassigned (handled as a special case).
Results. Updates arrive in seconds instead of up to 15 minutes. API calls fell from about 2,800 an hour to about 3,000 a day. Database load fell by 90 percent and CPU spikes by 50 percent, and the system supports five times the case volume.
Overlooked constraints.
- Ordering by timestamp. Two quick reassignments can arrive out of order. Applying an update only if its timestamp is newer than the stored one keeps the latest.
- Webhooks are a contract with a vendor. A Freshdesk platform change could break the app. Reconciliation is the insurance.
- Shadow mode needs a comparator. Running two paths is only useful if you count and diff their results, which the team did.
What Razorpay sacrificed. A small amount of vendor lock-in (code running inside Freshdesk) and the complexity of two paths, push and reconcile, in exchange for real-time updates and a 20x cut in API usage.
Deep Dive: when to push, when to pollShow
The cost model (handbook's illustration). Polling cost is independent of how much changes: (calls per poll) × (polls per hour). Push cost scales with change rate. If 300 tickets change an hour, push costs 300 webhook calls an hour, while polling every 15 minutes over a 4-day window might cost thousands. If 100,000 tickets changed an hour, polling a paged "changed since" query could become cheaper than 100,000 webhooks.
Latency. Polling every T minutes gives a mean staleness of T/2 and a worst case of T. Push gives roughly network latency plus processing, typically under a second.
Reliability. Push can lose events silently; polling sees the source of truth. The robust pattern is the one Razorpay used: push for latency, plus periodic reconciliation for completeness. Reconciliation at 3 hours means a lost event is fixed within 3 hours at worst, while normal events arrive in seconds.
The interview link. This is the same choice as real-time updates in an online auction: how do you show the current highest bid at once? You push changes over WebSockets or server-sent events, and let clients re-fetch on reconnect to fill gaps. Push gives freshness; a pull on reconnect gives correctness.
Family 5: The data platform
Lesson 11: Real-time denormalised streaming platform, part 1: the problem (2023)#
Assumptions.
- Traffic: 3 to 6 million change events every 10 minutes across the payment tables.
- Latency: merchant reports should be under an hour stale, down from up to 24 hours.
- Consistency: 100 percent accuracy. These are financial reports; a wrong total is a support ticket or a compliance problem.
- Maintenance: more than 30 schema change requests a quarter, and facts with 300 to 400 columns.
What a "fact" is. Merchant reports (settlements, payments, refunds) are served from facts: wide, denormalised tables where the joins between payments, orders, refunds, settlements and merchants are done in advance. Denormalised means data is copied and combined so a report reads one table instead of joining many at query time. Facts are fast to read but expensive to keep fresh.
The old pipeline. Facts were rebuilt daily. An Airflow job (a workflow scheduler) started a Spark job, driven by a JSON configuration describing the fact, which recomputed the whole fact from the company's first day and wrote it to S3 in Delta Lake format. That took 7 to 8 hours on more than 15 EC2 machines. Reports were up to a day stale. For real-time needs, a lambda-style design merged the daily fact with a near-real-time store at query time. That is two systems, with two sets of logic that must agree.
Goals. Freshness under an hour, and incremental refresh: update only what changed instead of recomputing everything.
Why it is hard. The part 1 post lists the challenges:
- Volume and mutability. Millions of events every 10 minutes, and old rows change: a refund can arrive two years after the payment.
- Range queries. Merchants query any date range since they joined.
- Accuracy: must be exact.
- Complex joins. Many tables, too large to broadcast to every worker.
- Schema churn. 30 or more change requests a quarter.
- The store. A fact has 300 to 400 columns and terabytes of data. A relational database does not scale to that cheaply, a NoSQL store is costly at that size, and S3 is cheap but its objects are immutable, so updates mean rewriting files.
Primary and secondary updates. Changes arrive through CDC (change data capture, using tools such as Maxwell or Debezium that read the database's replication log) into Kafka, and Spark Structured Streaming consumes them. Suppose a payments fact has payments as its primary table and orders, refunds and merchants as secondary tables. A change to a payment row is easy: it maps directly to one fact row. A change to an order row is hard: you must find every payment linked to that order, which means an index from the order to the payment's key and its partition (facts are partitioned by created_date). Then you rewrite those rows. Because S3 objects are immutable, rewriting means rewriting whole files.
Why S3 anyway. It is cheap at hundreds of terabytes, handles millions of updates in 10 minutes well when they are colocated in a few files, and suits the large scans reports need. The challenge is making updates efficient.
The dependency tree. With five tables, A to E, the joins form an N-ary tree: A (primary) joins B and C; C joins D; D joins E. Updates can arrive at any node. The post names four complications:
- High cardinality. One row in B (say a merchant) can link to millions of rows in A (payments). One update fans out to millions of fact rows.
- Missing dependent updates. If D changes, you must walk up through C to A to find affected fact rows.
- One-to-many joins. If A has many C rows, the fact's key becomes a composite such as (A.id, C.id, D.id).
- Multiple events for one change. A refund can update the payment (status refunded) and insert a refund row. Both events affect the same fact row.
The first solution. TiDB, a distributed SQL database compatible with MySQL, served as a near-real-time lookup store holding recent copies of the tables. For each micro-batch: read the primary-table events and traverse forward through the tree with lookups to build full rows; read secondary events and back-traverse to find the affected primary rows; join; upsert into Delta Lake; and park rows that could not be joined yet in a temporary table. Part 2 explains the engine.
Overlooked constraints.
- Late, old updates. Partitioning by created_date works for scans, but a refund two years later rewrites a two-year-old partition. Every partition is potentially hot.
- Schema change is a product requirement. With 30 changes a quarter, the pipeline must be config-driven, or engineers spend all their time rewriting jobs.
- Accuracy needs proof. A streaming fact must be checked against a batch rebuild until people trust it.
What Razorpay sacrificed. The simplicity of the daily full rebuild, which is correct by construction. Incremental pipelines are faster but much harder to get exactly right.
Deep Dive: incremental view maintenance in plain termsShow
The idea. A fact is a materialised view: F = A join B join C join D join E. When one table changes by a delta, the change in F is (delta A join B join C ...) plus (A join delta B join C ...) and so on, plus cross terms when several tables change at once. Databases call this incremental view maintenance. Razorpay's forward traversal computes the delta-A term; back-traversal computes the others.
Fan-out cost (handbook's illustration). A merchant row changes its display name. That merchant has 30 million payments. One CDC event becomes 30 million fact-row updates spread over every created_date partition, so effectively the whole merchant's data is rewritten. This is why such updates are pushed to a staging area and merged off-peak (part 3), or why some columns are better looked up at query time instead of denormalised.
Why not join at query time? Joining 300-column tables over terabytes for every report is slow and costly. Denormalisation moves cost from reads to writes. The question is which columns change often enough that denormalising them costs more than it saves. Rarely changing, widely used columns (merchant category) should be denormalised; frequently changing ones should not. See data modelling.
Lesson 12: Real-time denormalised streaming platform, part 2: the engine#
Assumptions.
- Traffic: as part 1, millions of events per micro-batch.
- Latency: each micro-batch must finish before the next starts, or lag grows.
- Consistency: every fact row must reflect the latest version of every joined row.
- Maintenance: new facts must be defined by configuration, not code.
Configuration drives everything. Each fact is a JSON document with a name and version; a source configuration (Kafka topics and batch duration); the primary table; the join tables with their join type and join condition; the lookup configuration; and the sink configuration (Pinot or Delta, with primary and partition keys). The engine parses it into a dependency graph: an N-ary tree with forward links from parent to child and back links from child to parent.
One micro-batch. Kafka events become a Spark dataset, and the engine visits nodes level by level (breadth-first). At each node it:
- Filters the relevant events.
- Repartitions by primary key and deduplicates, keeping only the latest version of each record in the batch.
- Joins with lookups.
- Upserts into the sink.
The primary flow. For events on the primary table, each Spark partition collects the distinct join keys and runs batched lookups, such as SELECT ... WHERE id IN (a list of distinct ids), one level at a time. Lookups for nodes on the same level run in parallel. Results go into a hashmap per table, are merged into full fact rows, converted to an Avro-based DataFrame and upserted into Delta Lake.
The secondary flow. For events on a secondary table, the engine back-traverses to the root to find the primary keys and partition keys of the affected fact rows, then does a partial-row upsert, updating only the columns from that table. Delta Lake supports updating some columns of matched rows.
Unjoined records. Microservices write their tables independently, so events arrive out of order. The post gives three cases: an order arrives before its payment is synced; a payment arrives with a null order ID; or the payment never happens. Records that cannot be joined yet go to a temporary table and are retried every batch, with a TTL (two years by default). The problem, which part 3 solves, is that this table keeps growing and every batch must re-scan it.
A partial-row upsert (handbook's illustration, Delta Lake SQL):
MERGE INTO payments_fact AS f
USING order_updates AS u
ON f.payment_id = u.payment_id
AND f.created_date = u.created_date -- partition value enables pruning
WHEN MATCHED AND u.order_updated_at > f.order_updated_at THEN
UPDATE SET f.order_status = u.status,
f.order_receipt = u.receipt,
f.order_updated_at = u.order_updated_at;Overlooked constraints.
- Partition values must be known. Without created_date in the match condition, Delta must scan every partition. Back-traversal exists partly to fetch it.
- Deduplicate before joining. Five updates to one payment in a batch should cost one join, not five.
- Out of order is normal. In a microservice system, joined data almost never arrives in join order.
What Razorpay sacrificed. Lookup-store cost and freshness coupling (the fact is only as fresh as the lookup store), and the growing cost of re-processing unjoined records each batch.
Deep Dive: why batched IN lookups beat per-row lookupsShow
Round trips (handbook's illustration). 42,000 primary rows, each needing an order and a merchant. Per-row lookups: 84,000 queries at 2 ms each is 168 seconds serially. With 200 partitions in parallel, 0.84 s, but 84,000 queries hit the store. Batched: each partition issues one IN query per table with about 210 distinct IDs; merchants dedupe heavily (perhaps 20 distinct per partition). That is 400 queries in total, at maybe 10 ms each. Roughly 200 times fewer round trips.
The limit of IN. Very long IN lists hurt query planning and packet sizes. Chunk them at a few hundred to a few thousand IDs.
Level-order matters. Level 2 lookups need keys from level 1 results (order items need order IDs), so levels are sequential, but nodes within a level are independent and parallel. The batch's critical path is the depth of the tree, not its size.
Lesson 13: Real-time denormalised streaming platform, part 3: making it fast#
Assumptions.
- Traffic: as before, with heavy duplicate work from secondary updates.
- Latency: micro-batches must stay within budget as data grows.
- Consistency: exact, including for late parents.
- Maintenance: tunable through Delta and Spark settings rather than custom code.
Why Delta Lake. The team compared Delta Lake, Apache Hudi and plain Parquet files against their needs: upserts, cheap scalable storage, fit with existing infrastructure, Spark support, ACID transactions, indexing, querying from Trino through Querybook (their SQL notebook), compression and community. Delta won. Its known weaknesses: two writers cannot update the same files at once; copy-on-write makes updates slow because whole files are rewritten; and you need the partition values to prune files.
Optimisation 1: a broadcast cache to skip duplicate work. Joins are commutative. An event on a refund (Er) and an event on its payment (Ep) both produce the same joined fact row (payment P1 with refund R1). If the primary flow already joined R1's latest version into P1, the secondary event for R1 is redundant. So after a node is processed, the engine stores, for each joined child record, its updated_at time and a SHA-256 hash of its contents, keyed by entity and primary key. This cache is broadcast to all executors, and secondary events whose version is already reflected are filtered out. The post reports this removes up to 70 percent of secondary updates.
Optimisation 2: Z-ordering. Delta can sort data within files by several columns using a Z-order curve (a way of interleaving the bits of several columns so rows close in all of them are stored close together). The team Z-ordered on the primary key and merchant ID, so a MERGE touches fewer files and merchant reports read fewer files. Originally Z-ordering ran every six batches on partitions changed in the last 15 days. A multithreaded version that works on partition ranges in parallel, built with Databricks, made it 75 percent faster.
Optimisation 3: low-shuffle merge. In a standard MERGE, Delta rewrites matched files, shuffling even unmodified rows and destroying their Z-order. Low-shuffle merge keeps unmodified rows in place, so Z-order survives. The team also tuned file size: files that are too small mean metadata overhead and lots of kilobyte files; files that are too large mean each update rewrites more data. They used Delta's optimised writes to produce well-sized files.
Optimisation 4: no more unjoined table. The temporary table was dropped. Instead, the new secondary flow traverses both ways: back to the root to find the affected primary rows, and forward to the leaves, so that when a late parent arrives, its children are found by lookup. Late arrivals no longer need parking.
Parallelism. Nodes on the same level run in parallel. Not all nodes can, because a node's cache filtering depends on its parent having been processed.
Settings named in the post (key names in this block are the handbook's rendering):
# Handbook rendering of the settings the post names; exact key names vary by Delta and Databricks version
spark.databricks.delta.optimizeWrite.enabled: true
spark.databricks.delta.autoCompact.enabled: false
spark.sql.adaptive.enabled: true
spark.databricks.delta.maxFileSize: 134217728 # 128 MB
spark.databricks.delta.merge.enableLowShuffle: trueRemaining pain points. High-cardinality updates, such as one settlement touching millions of rows, go to a staging area and are merged in off-peak hours. Writes to Delta for each entity are sequential. The partitioning scheme is still an open question. Schema changes need monthly backfills. And aliases need care when one table appears in the tree more than once.
Monitoring. Spark jobs export metrics through a Prometheus client to a VictoriaMetrics agent, stored in VictoriaMetrics and shown in Grafana. Key metrics: batch latency, throughput, source-to-target lag and pipeline status.
Overlooked constraints.
- A cache must never skip real changes. Using both updated_at and a content hash protects against two different versions with the same timestamp.
- Compaction competes with writes. Z-ordering and optimisation jobs rewrite files the stream also wants to update. Delta's lack of concurrent writes to the same files means scheduling matters.
- Backfills are inevitable. A new column means recomputing it for all history. Plan for monthly backfills, not none.
What Razorpay sacrificed. Engineering effort and tuning complexity: caches, Z-order schedules and file-size tuning are all things a daily batch never needed. Some update types still run in off-peak batches, so not everything is real time.
Deep Dive: what Z-ordering buysShow
File skipping (handbook's illustration). A fact of 2 TB in 128 MB files is about 16,000 files. A merchant report filters merchant_id = M. Without clustering, the merchant's rows are spread across almost every file, so the engine reads 16,000 files. Delta keeps min and max statistics per column per file. If data is Z-ordered on merchant_id, each file covers a narrow range of merchants, and the engine might read 20 files: about 800 times less I/O.
Why Z-order rather than sort. Sorting by merchant_id alone makes merchant queries fast but scatters a given payment_id range. MERGE on payment_id then touches many files. Z-order interleaves both columns, so both filters skip well, at some cost to each compared with a pure sort.
Write amplification. A MERGE that updates 1 row in a 128 MB file rewrites the whole file. If 1 million updates spread over 10,000 files, the batch rewrites 1.28 TB. If Z-order clusters them into 500 files, 64 GB. Clustering by the update key cuts write amplification as well as read I/O. See storage engines for the same trade-off in LSM trees.
Lesson 14: Trino and Alluxio analytics (2022)#
Assumptions.
- Traffic: about 650 daily active users and about 100,000 queries a day from dashboards (Looker), ELT jobs (Airflow) and ad hoc analysis.
- Latency: interactive queries in seconds to a minute; the reported P90 is 60 s and P95 is 130 s.
- Consistency: analytical data may lag production; queries must not fail randomly.
- Maintenance: a small platform team, self-managed on Kubernetes.
Background. In mid-2021, Razorpay moved away from a third-party data platform vendor. Spark workloads moved to Databricks, and the team built a self-managed Trino platform with an Alluxio cache on Kubernetes. The data lake: Spark jobs replicate OLTP data into S3 using Apache Hudi, with a Hive Metastore holding table definitions. Trino is a distributed SQL query engine that queries data where it lives; the team chose it over PrestoDB (its ancestor) for its container support and active community.
Separate clusters per workload. BI dashboards, ELT and ad hoc queries have different shapes. ELT runs long and heavy; dashboards need predictable latency. Each gets its own Trino cluster so one cannot starve another. Setup: the community Helm chart, Prometheus monitoring, Trino resource groups to cap concurrency, anti-affinity so each worker gets its own machine, and the cluster autoscaler. Query analysis used a fork of an open-source query analyser.
Alluxio, the cache. Two problems drove it: listing metadata on S3 is slow, and repeated reads of the same data cost money and time. The team needed a cache shared across clusters, covering both data and metadata, with block-level access, on Kubernetes. Alluxio is a distributed caching layer between compute and storage. It was deployed as a separate remote cluster, not colocated with Trino workers, so the two can scale independently and losing spot Trino nodes does not wipe the cache. It runs as a StatefulSet with multiple masters and an embedded journal, plus a catalog service. A Kubernetes CronJob syncs metadata between Hive and Alluxio's catalog; file-level sync depends on access patterns and expiry. The post reports improved P75, P90 and P95 latencies.
Availability across zones. A single Trino cluster is a single point of failure, and workers in different availability zones (AZs) exchange lots of data during queries, which AWS charges for. The solution: Trino clusters per AZ behind a load balancer, and Alluxio per AZ too. A router is needed to send each query to a cluster. The team looked at Lyft's open-source Presto gateway (limited routing) and another (tied to PrestoDB), and built their own Trino-Gateway in Go: a gateway server (admin APIs, query history), a monitor (health checks with SQL probes) and a router (least-load or round-robin). Clusters can be enabled and disabled on a cron schedule.
Autoscaling. Trino autoscaling is tricky: a query fails if a worker it uses shuts down, workloads differ, and you cannot compute an ideal size in advance. Kubernetes HPA and KEDA were rejected: they react to instant metrics and thrash, and do not offer configurable cooldowns. The team built a custom autoscaler driven by Alertmanager webhooks: alert rules with a "for" duration decide when load is sustained, and the scaler adds or removes workers in configured batch sizes with cooldowns. Scheduled scaling also takes clusters between zero and one worker for predictable quiet hours.
Scale. About 650 daily users and about 100,000 queries a day, P90 60 s, P95 130 s, about 97 percent success.
Overlooked constraints.
- Cross-AZ data transfer is a real bill. Distributed joins shuffle data between workers. Keeping a cluster in one AZ avoids paying for that traffic.
- Graceful worker shutdown. Removing a worker mid-query fails the query. Trino's graceful shutdown drains first, which slows scale-down.
- Caches need invalidation. If the lake changes and Alluxio's metadata does not, queries see stale file lists. Sync jobs are part of correctness.
What Razorpay sacrificed. Vendor support and simplicity: running Trino, Alluxio, a gateway and an autoscaler is real platform work. It gained control over cost, performance and availability.
Deep Dive: when a cache in front of S3 pays offShow
Latency (handbook's illustration). An S3 GET has a first-byte latency of tens of milliseconds; LIST over a large prefix can take seconds. Alluxio serving from memory or local NVMe answers in under a millisecond to a few milliseconds. A query that touches 2,000 files, opening each with a 30 ms latency at 64-way parallelism, spends about 1 s just on first bytes. Cached, that falls to tens of milliseconds.
Cost. S3 charges per request and for data transfer out of a region or to the internet, not for transfer to EC2 in the same region. The savings are mainly request counts and latency, plus avoiding cross-AZ traffic when the cache is per AZ.
Hit rate is everything. Dashboards querying the last 7 days repeatedly have high hit rates; ad hoc scans of years do not. Size the cache for the hot working set, not the lake.
Relation to the classic pastebin question. The primer's pastebin design computes page-view analytics with a MapReduce job over web logs, because analytics need not be real time. Razorpay's story shows the next step: when analytics become a product for 650 users, you need an interactive engine, caching and isolation, and when reports must be fresh, you need the streaming facts from Lessons 11 to 13. See data pipelines and analytics.
Family 6: Observability and incidents
Lesson 15: Trillions of metric points (2016 to 2021)#
Assumptions.
- Traffic: grew from about 30 services in 2016 to more than 100 across several Kubernetes clusters by 2020, with high-cardinality business metrics.
- Latency: dashboards should load in seconds even over long ranges; alerts must evaluate every minute or faster.
- Consistency: metrics can be slightly late; alert evaluation must not silently miss data.
- Maintenance: a small infrastructure team; the system must be cheap and simple to run.
Era 1: one Prometheus (2016 to 2018). Razorpay has run Kubernetes in production since late 2016. Traditional monitoring tools such as Nagios and Icinga were not built for containers that come and go. The team ran Prometheus as a StatefulSet with storage on EBS volumes, scraping node exporter (machine metrics), cAdvisor (container metrics), the kubelet, kube-state-metrics (Kubernetes object state), a CloudWatch exporter for AWS services, application client libraries, and a statsd bridge for legacy apps that push metrics. Grafana showed dashboards; Alertmanager routed alerts to Slack and PagerDuty.
Problems appeared as load grew: no high availability (one instance), slow long-range queries, only vertical scaling, reads and writes competing on one process, and recurring out-of-memory, CPU and upgrade problems.
Era 2: Thanos (2018 to 2020). With multiple clusters and more than 100 services, the team added Thanos, which gives Prometheus high availability, long-term storage in S3 and a global query layer, and Trickster, a cache for dashboard queries. It helped, but brought new problems: queries over old data fetched blocks from S3 and then computed, which is slow; S3 listings over a flat directory structure were slow; data was uploaded to S3 only every few hours; dashboards timed out and the Thanos store process ran out of memory. It cost about 12,000 dollars a month, and running Prometheus in HA pairs doubled ingestion cost.
High cardinality. The core difficulty was business metrics. A query like sum(rate(payment_create_http_requests[2m])) is cheap. Add labels for payment method, network or bank, international or domestic, transaction value band and merchant category code, and every combination becomes its own time series. Cardinality is the product of each label's distinct values, and it explodes. See time-series databases.
Era 3: choosing a replacement (2020). The team ran proofs of concept:
- M3DB was rejected because the team wanted the open Prometheus format and a broader community.
- Thanos was the incumbent and did not fix the problems.
- Cortex had several problems in the test. Ingesters held data in memory and, when they failed, metrics were lost. S3 support lacked the request signing they needed, which pushed them to Cassandra. DynamoDB support meant cloud lock-in. Redis caching was only experimental, so they used Memcached. The test setup needed 10 ingesters, 5 distributors, 3 Consul and 5 Cassandra nodes, none suitable for spot instances, and high-cardinality queries still failed.
- VictoriaMetrics won. It is simple, with separate horizontally scalable components for insert (vminsert), storage (vmstorage) and select (vmselect), so reads and writes scale separately. Defaults worked, retention was configurable (a month by default), compression was about 70 percent better in their tests, stateless parts ran on spot instances, and it handled the worst dashboards.
Migration in under a month across four clusters. Prometheus was configured to remote-write to VictoriaMetrics in parallel; problem dashboards were pointed at vmselect to compare; the cluster was tuned; stateless parts moved to spot instances; then Grafana and Alertmanager were switched over in one night. The team then added vmalert for alert rules and replaced Prometheus with vmagent, a lightweight, stateless scraper that can run in HA and on spot instances and removed the write-ahead-log corruption problems they had with Prometheus. A small separate VictoriaMetrics cluster monitors the main one.
Cost. Only vmstorage runs on on-demand instances: 5 nodes at about 13 dollars a day. vmselect, vminsert and vmalert run fully on spot with HPA (about 3 spot nodes, about 3 dollars a day), and vmagents about 2 dollars a day. That is about 18 dollars a day, excluding EBS and data transfer, against roughly 400 dollars a day for the Thanos setup.
Next steps and lessons. Detect and limit cardinality from third-party software, extend retention from one to three months, and export metrics to the data lake. The authors' lessons: keep it simple, prefer open standards, do not trust marketing (test it), and run operational reviews against real outcomes, not vanity metrics.
Overlooked constraints.
- Cardinality is a product decision. Every label a team adds multiplies cost. Limits and reviews are needed, or a single deploy can add millions of series.
- The monitor needs a monitor. If the metrics cluster fails, alerts stop. A separate small cluster watching it is cheap insurance.
- Migrations need parallel runs. Remote-writing to both systems let the team compare before switching.
What Razorpay sacrificed. Long retention (one month by default at first) and some of the ecosystem around Thanos and Cortex, in exchange for a simpler, cheaper and faster system.
Deep Dive: sizing a metrics platformShow
Cardinality (handbook's illustration). payment_create_http_requests with labels method (6), bank or network (60), international (2), value band (5) and merchant category (40) gives 6 × 60 × 2 × 5 × 40 = 144,000 series for one metric, before multiplying by pods (say 50): 7.2 million series. At one sample every 15 seconds, that is 480,000 samples a second from a single metric.
Storage. Good time-series compression (delta-of-delta timestamps and XOR-encoded floats, the scheme from Facebook's Gorilla paper by Pelkonen and others, 2015) stores a sample in about 1 to 2 bytes. 480,000 samples a second × 1.5 bytes × 86,400 s ≈ 62 GB a day for that one metric. Dropping the pod label (aggregate before storing) cuts it 50 times.
The interview problem. The metrics-monitoring problem in interview guides assumes 500,000 servers each sending 100 metrics every 10 seconds: 5 million points a second, at 100 to 200 bytes raw each, about 1 GB/s before compression. The two hard parts it asks about map directly onto Razorpay's story:
- Ingesting metrics from services: pull (scrape, as Prometheus and vmagent do) versus push (statsd, OpenTelemetry), with a stateless, horizontally scaled ingest tier (vminsert) in front of sharded storage (vmstorage).
- High availability during spikes and failures: keep ingest stateless and replicated, buffer at agents during storage hiccups, replicate storage, run a separate meta-monitor, and alert on missing data as well as bad data. Amazon's trick of alerting on "milliseconds since the last order" catches pipelines that go silent.
See the metrics monitoring case study.
Lesson 16: The observability and tracing journey (2017 to 2022)#
Assumptions.
- Traffic: about 8 TB of span data a day if every request were traced.
- Latency: traces should be searchable within minutes; old traces must be queryable for compliance.
- Consistency: sampled data is fine, but errors and slow requests should always be kept.
- Maintenance: a mix of PHP (Laravel) and Go services; any tracing SDK must support both.
Six rules from the post. The tracing post frames observability as an engineering investment with rules worth repeating:
- Do not build it unless you need it.
- Try the cheapest options first: explore before you exploit.
- Go step by step: structured logs first, then metrics with Prometheus and Grafana, then tracing.
- At around 30 services or 200 engineers, evaluate build versus buy on total cost of ownership.
- Scale, tune, repeat.
- When unsure, go back to rule 1.
The APM era. From 2017 the Laravel monolith used a commercial APM (application performance monitoring) agent, which captured app metrics, slow queries, external calls and AWS metrics. From late 2017, Razorpay started building Go microservices. The APM agents did not support Go well, usage fell, and the cost was high. The team had questions the APM could not answer: engineering questions (why did this endpoint slow down?), business questions with high cardinality (which merchant on which route?), operational questions (SLIs and SLOs, baselines, detecting changes) and cultural ones (how do teams own their reliability?).
The gaps. Call chains were getting deeper. "Microservices are not a collection of monoliths": per-service views miss what happens between services. Pricing did not scale. There was no dependency map. Finding the hotspot meant hopping between dashboards. Slow-query analysis depended on database administrators. And engineers suffered from log fatigue.
Distributed tracing. The team adopted open formats: OpenCensus and OpenTracing, which have since merged into OpenTelemetry, following the lineage of Google's Dapper paper (Sigelman and others, 2010). The model: a trace is one request's journey; it is made of spans, each a timed operation in one service with a parent; spans carry tags such as merchant ID, route and status. They built a custom Go SDK and forked the PHP OpenCensus library.
Why not SaaS. They evaluated 8 to 10 vendors. Common gaps: limited historical queries (a fintech must replay old flows for compliance and disputes), on-premises samplers required, and opaque pricing.
Sampling and storage. Spans per day = requests × spans per trace × bytes per span came to about 8 TB a day unsampled. They chose to sample successful (2xx) requests at 1 in 20 and keep everything else. With 95 percent of traffic successful, that keeps 95/20 + 5 = 9.75 percent of requests; the post rounds it to about 10 percent (it states 9.6). That is about 1 TB a day, or roughly 30 TB a month.
Choosing a backend. Apache SkyWalking was Java-centric. Expedia's Haystack was complex and its Elasticsearch storage would have cost about 46,000 dollars a year; Cassandra was a bottleneck for both Haystack and Jaeger at their scale. They chose Jaeger, while noting its limits: no RED metrics (rate, errors, duration) derived from spans, a limited dependency graph and no drill-down by business entity. The next step they named was Hypertrace, which builds on Jaeger data with those features.
Overlooked constraints.
- Head sampling can miss the interesting trace. Deciding at the start which traces to keep cannot know whether a request will be slow. Keeping all non-2xx helps, but slow successes are sampled away unless tail-based sampling is used.
- Context must cross languages. PHP and Go services must propagate the same trace headers, or traces break at every boundary.
- Compliance changes retention. Fintech needs long, queryable history, which shapes storage choice more than performance does.
What Razorpay sacrificed. Completeness (about 90 percent of successful traces are dropped) and SaaS convenience, in exchange for cost control, open formats and the historical queries compliance needs.
Deep Dive: the trace storage arithmeticShow
Working it through (handbook's illustration). Suppose 200 million requests a day, 20 spans a trace and 2 KB a span: 200M × 20 × 2 KB = 8 TB a day, matching the post's order of magnitude. Sampling 2xx at 1 in 20 with a 95 percent success rate keeps 9.75 percent: about 780 GB a day. With indexes and replication, about 1 TB.
Head versus tail sampling. Head sampling decides at the first span; it is cheap and needs no buffering. Tail sampling buffers all spans of a trace (for perhaps 10 to 30 seconds) and decides after it ends: keep if slow, errored or touching a rare path. It needs a stateful collector tier sized for the buffer: at 8 TB a day, about 93 MB/s, a 30-second buffer is about 2.8 GB in memory across collectors. That is affordable and catches slow successes that head sampling drops.
Exemplars connect metrics to traces. Attaching a trace ID to a histogram bucket sample lets an engineer jump from a P99 spike on a dashboard straight to a trace that caused it. This closes the "hotspots across dashboards" gap. See observability.
Lesson 17: Managing production alerts as code (2021 to 2022)#
Assumptions.
- Traffic: hundreds of alert rules across many teams and business units.
- Latency: mean time to acknowledge (MTTA) and mean time to engage (MTTE) were about 15 minutes; the goal was under 2.
- Consistency: every business metric that matters must have an alert, and every alert must have an owner.
- Maintenance: teams should add alerts themselves without asking DevOps.
The trigger. A summer 2021 incident caused by an external attack led to a review in three areas: application (circuit breakers and rate limits), database (connection limits and throttling) and infrastructure (faster MTTD and MTTE). This post, the third in a series, covers alerting.
Goals. Monitor all business metrics; make alert onboarding self-service; reduce MTTA and MTTE; and give incident response a fixed structure.
What was wrong. Alert configurations were created by hand in Grafana and Prometheus, scattered with no single source of truth. Syntax errors broke rules silently. DevOps was the default owner of every alert. Incident logistics (a Slack thread, a Zoom call, a Jira ticket) were set up by hand, and the on-call engineer was also handling communication while trying to fix things.
The new system.
- Alerts as code. Alert rules live in Git and change through pull requests. A CI check validates syntax (YAML) and semantics: each rule must have a title, a service tag and a business unit tag.
- Sync. A cron job pushes rules from Git to the VictoriaMetrics rule engine (vmalert). Alertmanager posts firing alerts to Slack.
- An incident Slack bot reads the alert's metadata, pages the owners through PagerDuty by business unit and service, creates a dedicated incident channel and a recorded Zoom bridge, and opens a Jira ticket for the RCA.
- Thresholds are tested in the performance environment first, so they are not guessed in production.
- A command center owns communication (next lesson), freeing engineers to fix.
The alert format. Each rule has an alert name, a PromQL expression, labels (severity, business unit, service, whether it is live, impact) and an annotation with a description. An example (handbook's illustration in that shape):
- alert: PaymentSuccessRateDropUPI
expr: |
sum(rate(payments_success_total{method="upi"}[5m]))
/ sum(rate(payments_attempt_total{method="upi"}[5m])) < 0.6
for: 3m
labels:
severity: P0
bu: payments
service: upi-gateway
live: "true"
impact: customer-facing
annotations:
description: "UPI success rate under 60 percent for 3 minutes. Runbook: upi-sr-drop"Result. MTTA and MTTE fell to under 2 minutes, from about 15.
Overlooked constraints.
- Alert fatigue. Self-service makes adding alerts easy; it must also make deleting noisy ones easy, or the pager becomes noise.
- Sync lag. A cron-based sync means a merged rule takes effect minutes later. Fine for alerts; not for emergency silences.
- Owner metadata rots. Teams reorganise; service and BU tags must be validated against a live ownership registry.
What Razorpay sacrificed. The ability to tweak alerts quickly in a UI. Every change now goes through review. In exchange, every alert has an owner, a history and a valid syntax.
Deep Dive: what MTTA under 2 minutes is worthShow
Breaking down an incident. Time to recover = time to detect + time to acknowledge + time to engage the right people + time to diagnose + time to fix. Razorpay attacked the early, mechanical stages: detection by alerts on business metrics, acknowledgement by direct paging, and engagement through the bot's automated channel, Zoom and owners.
The value (handbook's illustration). A degradation costs 1,000 failed payments a minute. Cutting MTTA and MTTE from 15 to 2 minutes saves 13,000 payments per incident. At 10 such incidents a month, that is 130,000 payments a month, with no change to the fix itself.
Alerts on symptoms, not causes. The best payment alert is on success rate (a symptom the customer feels), not CPU (a cause that may not matter). Symptom alerts catch unknown causes. Cause alerts help diagnosis and belong on dashboards or at low severity. See observability and Google's SRE guidance on alerting from service-level objectives.
Lesson 18: The incident command center and better 5-why RCAs (2021 to 2022)#
Assumptions.
- Traffic: incidents that span several teams, with business teams waiting for updates.
- Latency: time to acknowledge, engage and recover (TTA, TTE, TTR) all matter, and communication must be timely.
- Consistency: one timeline, one owner, one message to customers.
- Maintenance: a process people actually follow under stress.
The incident that changed things. On 12 August 2021, starting around 6:50 pm, an outage spread across several components. The command center post describes what went wrong in the response: teams worked in silos, nobody knew the cause after 45 minutes, and business teams were trying to decode technical conversations to tell merchants what was happening. The RCA post adds that it needed a dozen or more people. The post lists the underlying gaps: no end-to-end owner, no single person driving the call, poor triage, high MTTR, weak collaboration between technical and non-technical teams, poor communication and a bad customer experience.
The command center. Razorpay built a 24×7 Command Center team. Its job:
- Monitor alerts and open the incident call.
- Drive the call: keep it focused, track parallel workstreams, make sure each has an owner.
- Communicate to business, technical teams and leadership, so engineers do not have to.
- Record the timeline as it happens.
It targets TTA and TTE directly, and part of TTR. The post separates proactive alerts (the system detects the problem first) from reactive ones (customers or business teams report it); more than 90 percent are now proactive.
The flow. The bot posts the alert to Slack, pages the business unit head and the pod's owner, and creates the Jira ticket and Zoom bridge. An Incident Commander leads. Incidents start in a #potential_outages channel and move to #outages once customer impact is confirmed. After the incident, problem management takes over: an RCA within an agreed time, and preventive action items with their own deadlines.
Why 5-Why was not enough. Before, RCAs had no template, so depth varied, the GMV (gross merchandise value, the money that failed to flow) impact was often missed, and RCA meetings were spent filling gaps. Then the team adopted the 5-Why template: keep asking "why?" until you reach a root cause, for example, "Why did API response time hit 5 seconds?" The RCA post points out the flaw. Suppose an incident lasted an hour: 45 minutes to find the cause and 15 minutes to fix it. 5-Why explains why the failure happened, which helps prevention, but says nothing about why it took 45 minutes to find, which is where most of the time went.
Sequence of Events. The new template adds a timeline. For each timestamp, the team records the Event (what happened), the Action (what someone did), what was Missing (information, capability or a person that would have helped) and what was Missed (a step that should have been taken and was not). Examples from the post:
- Missing: a 10-minute lockout from the admin dashboard showed that throttles needed an isolated control plane; dashboards were scattered; there was no escalation policy; the Reminders service had no circuit breaker; network ACL updates ran from a notebook; new joiners lacked access.
- Missed: a late post to #outages; a daily database CPU alert that auto-resolved after 5 minutes and was ignored for 5 days; a problem misjudged as affecting a single merchant.
- Actions: check recent deploys; call DevOps; revert to the previous day's commit; pull the top errors in 15 minutes; add 10 pods above the HPA limit.
The post's result: RCA meetings became discussions about improvements instead of fact-finding sessions.
Overlooked constraints.
- Communication is a separate job. The person fixing the problem should not also be writing status updates.
- Recovery time is a design target. Missing tools (an isolated control plane, a fast revert) show up only when you analyse the timeline, not the root cause.
- Auto-resolving alerts hide patterns. A daily alert that clears itself is a signal, not noise.
What Razorpay sacrificed. Headcount and process overhead: a 24×7 team, Incident Commanders, RCA deadlines and action-item tracking. For a payments company with merchants waiting on every minute of downtime, that is cheap.
Deep Dive: reading an incident timelineShow
Where the time goes (handbook's illustration). For the one-hour example: detect 5 min, acknowledge 5 min, assemble people 10 min, diagnose 25 min, mitigate 15 min. 5-Why targets the cause (prevent next time). The timeline shows that 40 of 60 minutes were before mitigation began. Better alerts, paging and a command center cut detect, acknowledge and assemble to about 5 minutes, and a one-click revert cuts mitigation to 3, without knowing the root cause yet.
Mitigate first, diagnose later. The post's action list ("revert to the previous day's commit", "add 10 pods") are mitigations. The rule of thumb from incident practice: restore service by the fastest safe means, then find the cause. The incident management page covers roles (commander, communications, scribe, operations) and blameless postmortems.
Missing versus Missed. "Missing" items lead to engineering work (build an isolated control plane). "Missed" items lead to process work (runbooks, training, escalation rules). Separating them makes action items concrete and assignable.
Family 7: Product, experiments and security
Lesson 19: High availability of the payments dashboard (2021 to 2022)#
Assumptions.
- Traffic: the merchant dashboard is a large single-page application used by merchants all day to see payments, refunds and settlements.
- Latency: pages should load fast, but the main availability measure is crash-free sessions: sessions with no JavaScript crash.
- Consistency: a bad deploy must be caught before most merchants see it.
- Maintenance: more than 40 engineers in 16 teams changing about 12,000 files in one codebase.
Where it started. The dashboard post describes a frontend in poor health: crash-free sessions dropped as low as about 50 percent; error tracking reported about 7,000 crashes an hour, most of them false or unimportant, which buried the real ones and hurt detection time; MTTA was over two hours; and there were no automated checks in the delivery pipeline.
What they did.
- Ownership. Every route got an owning team. A React ErrorBoundary wrapper (a component that catches errors in the components below it) tags each error with the owning team and a priority. Routing rules map errors to teams by stack trace, file path and URL. Each team gets its own alerts and a custom dashboard. Errors that belong to everyone belong to no one; this fixed that.
- A fix deadline. Teams had two months to fix their existing errors.
- Pre-commit checks: lint, Prettier formatting, TypeScript compile and ESLint on the developer's machine.
- Post-commit checks on every pull request: PR size, changes to sensitive files, ESLint, TypeScript, a bundle-size diff (so nobody silently adds 500 KB), unit and integration tests, a coverage threshold and code-owner approval.
- Deploy-time checks: an end-to-end (E2E) test suite on the automation environment, then the same suite against production at 0 percent traffic: the new version is deployed but gets no real users, and if E2E fails, the deploy halts.
- Response: PagerDuty phone calls for real crashes, and weekly reviews of action items.
- Rollback: a one-click revert pipeline that takes 2 to 3 minutes, down from about 30.
Results reported. Crashes fell about 350 times, to roughly 20 an hour (about 28 errors an hour at the end of the period measured, May 2021 to January 2022). Crash-free sessions reached about 99.9 percent. The checks blocked 10 or more bad deployments out of about 100 in three months, and 10 to 15 percent of pull requests were blocked for breaking changes. MTTA fell to 2 to 3 minutes. Incidents fell from about 40 a month to about 7.
Overlooked constraints.
- Frontend availability is real availability. A merchant who cannot load the dashboard experiences an outage, even if every backend is up.
- Noise destroys signal. 7,000 mostly meaningless crashes an hour meant real ones went unnoticed. Cleaning up noise came before alerting.
- Zero-traffic production tests catch config drift that staging cannot, because they run against real production configuration and dependencies.
What Razorpay sacrificed. Developer speed: more checks per pull request, about 1 in 10 PRs blocked, and slower deploys. It was a clear trade for a dashboard merchants depend on.
Deep Dive: crash-free sessions as an SLOShow
Defining it. Crash-free session rate = sessions with no unhandled crash ÷ all sessions. It is a good frontend SLI because it measures what users feel. An SLO might be 99.9 percent over 28 days.
Error budget (handbook's illustration). At 2 million sessions a month, a 99.9 percent SLO allows 2,000 crashed sessions. A bad deploy that crashes 5 percent of sessions for 30 minutes, with 3,000 sessions an hour, burns 75 sessions. Reverting in 3 minutes instead of 30 cuts that to about 8. Fast rollback makes the budget last.
Why 0 percent traffic deploys work. Many failures come from configuration: environment variables, CDN paths, API URLs, feature flags. A production deploy with no users exercises all of it. The same idea, "deploy is not release", appears in feature flags and canaries; see deployment and CI/CD.
Lesson 20: Splitz experimentation#
Assumptions.
- Traffic: about 15,000 evaluation requests a second, with cohorts of over 10 million users or merchants.
- Latency: evaluation is on the request path, so P99 must be in low milliseconds; the post reports P99 of 12 ms and P95 under 4 ms.
- Consistency: a user must see the same variant every time, and a ramp from 3 to 4 percent must not reshuffle who is in.
- Maintenance: product teams run experiments and rollouts themselves.
What Splitz is. Razorpay's in-house platform for A/B tests (comparing variants, such as a grid versus a list view of payment methods on checkout) and gradual rollouts (ramping a change from 1 percent to 100 percent). It also serves as a feature-flag system: many experiments across time and environments, with ramps changed in near real time. The deadlock fix in Lesson 5 was rolled out through it.
The four building blocks.
- Sampling: a percentage from 0 to 100 that decides how much traffic enters the experiment.
- Exclusion groups: experiments in one group are mutually exclusive, so a user in experiment A is not also in experiment B when the two would interfere.
- Segments: lists of IDs, such as a set of pilot merchants.
- Audience rules: a rule engine built on JsonLogic (a format for expressing logic as JSON), with comparison operators (less than, greater than, equal, not equal) and set operators (belongs to, does not belong to). Example: merchant.location equals Bangalore.
Evaluation order: sampling, then exclusion, then audience rules (including segment checks), then a variant bucket is assigned.
Consistent bucketing. Assignment must be deterministic: hash the user ID with the experiment ID and map the result to a bucket. The hash must be fast, uniform, low-collision and pass the avalanche test (flipping one input bit flips about half the output bits). Splitz uses MurmurHash with a fixed seed. Because a user's hash value never changes, a user inside a 3 percent rollout (hash bucket below 3) is still inside at 4 percent: ramps only add users, never reshuffle them. This is the monotonic ramp property.
Segments with Bloom filters. Checking whether an ID belongs to a segment of 10 million IDs on every request is costly with a plain set lookup across the network. Splitz stores segments in RedisBloom, a Redis module for Bloom filters. A Bloom filter answers "definitely not in the set" or "probably in the set" using a bit array and several hash functions. For 1 million IDs at a false-positive rate of about 1 in 100,000, the post says it uses at most 3.3 MB and evaluates in under 10 ms. See probabilistic data structures.
Performance. 15,000 requests a second at P99 12 ms and P95 under 4 ms; segment evaluation P99 under 4 ms; other components take microseconds. Future work: local evaluation in client SDKs (under 5 ms with no network call) and dynamic segment updates.
Overlooked constraints.
- Bloom false positives leak users into experiments. At 1 in 100,000 the leak is tiny, but for compliance-sensitive rollouts the false-positive rate must be chosen on purpose.
- Hash seeds must differ per experiment. If every experiment used the same hash of user ID alone, the same 3 percent of users would be in every experiment, biasing results. Hashing user ID with experiment ID avoids that.
- Statistics are a separate problem. Assignment is only half of experimentation; analysis (sample size, sample ratio mismatch, peeking) is covered in the experimentation platform case study.
What Razorpay sacrificed. Exactness of segment checks (Bloom filters) and a network hop per evaluation, in exchange for memory efficiency and central control. Local evaluation trades back some control for latency.
Deep Dive: Bloom filter sizing and hash uniformityShow
Bloom filter math. For n items and false-positive rate p, the optimal bit count is m = −n ln p / (ln 2)² and the number of hash functions k = (m / n) ln 2. For n = 1,000,000 and p = 0.00001: ln p ≈ −11.51; m ≈ 1,000,000 × 11.51 / 0.4805 ≈ 23.96 million bits ≈ 3.0 MB; k ≈ 16.6, so 17 hashes. That matches the post's figure of at most 3.3 MB.
Monotonic ramps. Map the hash to a number h in 0 to 9,999. The user is in the rollout if h is below 100 × percent. At 3 percent, users with h under 300; at 4 percent, under 400. Every user in at 3 percent is in at 4 percent. This is like consistent hashing: changing a parameter only moves the minimum number of keys.
Uniformity check (handbook's illustration). With 10 million users and 100 buckets, each bucket expects 100,000 users with standard deviation about 316. A bucket off by more than about 1,000 (3 sigma) suggests a biased hash or a non-random ID scheme. Sequential IDs plus a weak hash, such as modulo, often fail this test; MurmurHash passes.
Lesson 21: Istio service mesh and mutual TLS (2023)#
Assumptions.
- Traffic: service-to-service calls inside Kubernetes, including card tokenisation traffic.
- Latency: encryption adds overhead; the post reports about 20 percent worse latency.
- Consistency: policy must be applied uniformly; one service without encryption is a gap.
- Maintenance: many teams' services, migrated without each team rewriting TLS code.
Why. The RBI tokenisation rules require protecting card data. Encryption at rest was covered; data in transit between services also needed encryption. Doing TLS in every service's code, across languages, with certificate rotation, is slow and error-prone. A service mesh moves it to infrastructure: an Envoy proxy sidecar next to each pod handles TLS, identity and traffic rules. Razorpay chose Istio for its community, stability and features.
Mutual TLS. In normal TLS, only the server proves its identity. In mutual TLS (mTLS), both sides present certificates, so the server also knows which service is calling. Istio issues each workload a certificate tied to its Kubernetes service account and rotates it automatically.
Traffic management. A VirtualService defines routing rules (by path, header and so on), evaluated in order. A DestinationRule defines what happens after routing, such as subsets by version (v1 and v2) for canaries. A Gateway controls traffic entering the mesh.
PeerAuthentication modes. PERMISSIVE (the default) accepts both mTLS and plain text, which allows gradual onboarding: services keep working while clients move to mTLS. STRICT accepts only mTLS. DISABLE turns it off. The mode can be set for the whole mesh, a namespace, a workload or a single port. Making the ingress gateway STRICT needs a TLS secret referenced by credentialName.
AuthorizationPolicy. A policy has a selector (which workloads it applies to), an action (ALLOW or DENY) and rules. Examples from the post's style: DENY requests whose principal is not a given service account; ALLOW only from the tokenization namespace. Rules can match values or exclusions, and there are patterns for allow-nothing, deny-all and allow-all, custom conditions, and plain TCP traffic.
# Handbook illustration of the two policies described above
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
name: default
namespace: tokenization
spec:
mtls:
mode: STRICT
---
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
name: allow-only-tokenization
namespace: tokenization
spec:
action: ALLOW
rules:
- from:
- source:
namespaces: ["tokenization"]Challenges. Pod Security Policies (a since-removed Kubernetes feature) had to be worked through for the sidecars, and latency got worse by about 20 percent. The post notes that AWS did not offer mTLS for this internal service-to-service case, while Istio gave centralised encryption and per-tenant traffic control.
Overlooked constraints.
- Sidecar latency adds up. Each hop adds two proxy passes. With deep call chains, a few milliseconds per hop become tens.
- PERMISSIVE is not secure. It is a migration state. A mesh left PERMISSIVE accepts plain text forever.
- Identity is only as good as service accounts. If many services share one service account, mTLS cannot tell them apart.
What Razorpay sacrificed. About 20 percent latency, extra memory and CPU per pod, and the operational cost of running Istio, in exchange for uniform encryption and identity-based authorisation without changing application code.
Deep Dive: where the mesh latency comes fromShow
Per hop (handbook's illustration). A call from A to B passes A's Envoy (outbound) and B's Envoy (inbound). Each pass costs perhaps 0.5 to 1 ms at P50 with TLS session reuse, more at P99. A request that fans through 5 services sequentially adds 10 proxy passes: 5 to 10 ms. If baseline latency was 40 ms, that is a 12 to 25 percent increase, consistent with the post's 20 percent.
Reducing it. Connection reuse (keep-alive, HTTP/2) avoids repeated TLS handshakes. Right-sizing sidecar CPU avoids queueing. Newer "sidecar-less" designs such as Istio's ambient mode move L4 mTLS to a per-node proxy and use L7 proxies only where needed.
Zero trust. mTLS plus authorisation policies implement the zero-trust idea: no service is trusted because of where it sits on the network; each call proves who it is. See security fundamentals and containers and Kubernetes.
Family 8: Synthesis
Lesson 22: What the Razorpay posts teach together#
The posts look like a collection of unrelated fixes, but a few patterns repeat across them.
| Pattern | Where it appears | What it buys | What it costs |
|---|---|---|---|
| Detect from symptoms, per cohort | Downtime detection, SR alerts, crash-free sessions | Fast, user-relevant detection | Statistics, noise handling, rule management |
| Route around failure automatically | ML gateway routing, P0 to P2 queues, per-AZ Trino | Survives partial failures | Model and router upkeep, less transparency |
| Isolate the slow from the fast | ProxySQL, per-merchant QoS, separate Trino clusters | One slow part cannot sink all | More components, more config |
| Make writes atomic locally | Outbox, consistent lock order | Correctness without distributed transactions | Delay, ordering limits, discipline |
| Push plus reconcile | Webhooks with 3-hour reconcile, daily balance reconciliation | Speed and completeness | Two paths to maintain |
| Configuration over code | Fact config, alert YAML, Splitz rules, broadcast commands | Self-service, fewer deploys | Validation and review needed |
| Verify the measurement | Perf-test dashboards, detector accuracy reports | Trustworthy decisions | Extra checking work |
| Process as a system | Command center, sequence of events, ownership tags | Faster recovery, clear ownership | People and process overhead |
What Razorpay sacrificed overall. Simplicity, most of all. Almost every lesson adds a component (a Flink job, a sidecar, a gateway, a bot, a team) or a process step (reconciliation, review, RCA deadlines). The company also accepted approximation in many places: fixed-window limits, sampled traces, Bloom filter segments, slightly stale routing scores. That buys speed and cost. The one place it never accepts approximation is money: balances, payment status and reports must be exact, and every such path has a reconciliation behind it.
Deep Dive: the reliability budget of a paymentShow
Composing it (handbook's illustration). A payment succeeds if Razorpay's path works (say 99.95 percent) and the chosen gateway and bank work. If one gateway is 99 percent available for a given method, a single-gateway design gives 0.9995 × 0.99 ≈ 98.95 percent. With two independent gateways and perfect routing, the probability both fail is 0.01 × 0.01 = 0.0001, so 0.9995 × 0.9999 ≈ 99.94 percent. Routing turns the partner's reliability from a product term into a nearly parallel term.
Where it breaks. Independence. If both gateways rely on the same issuing bank, the bank's failure is common to both and routing cannot help. That is why downtime detection is per issuer and why "inform the customer to use another method" is the last line of defence: it routes across banks, which only the customer can do.
What to measure. End-to-end success rate per cohort, time to detect a cohort degradation, time to reroute, and the share of incidents found proactively. Razorpay's posts report each of these in some form.
Cross-cutting: classic interview topics seen through Razorpay#
Several standard interview problems have deep-dive questions that Razorpay's posts answer with production detail.
Metrics monitoring: ingesting metrics and staying available during spikes. The interview version assumes 5 million points a second. Razorpay's path from one Prometheus to Thanos to VictoriaMetrics shows the answer in practice: a stateless, horizontally scaled ingest tier; storage separated from querying; agents that buffer; spot instances for stateless parts; a meta-monitoring cluster; and strict control of label cardinality (Lesson 15). Alert rules over windows ("P99 above 500 ms for 5 minutes") are exactly the "for" clause in Lesson 17's YAML.
Ad-click aggregation: real-time analytics with stream processing. The strong answer streams clicks through Kafka into Flink with event-time windows and watermarks, then into an OLAP store, partitioned by ad ID to scale writes. Razorpay's downtime detector (Lesson 2) is the same architecture with payments instead of clicks: keyed streams, windows, state cleanup and side outputs for audit. The custom dynamic window shows one more step: windows whose size changes at runtime. See scaling writes.
Online auction: showing the current highest bid in real time. The question is really about push versus pull and about consistency of the "current" value. Lesson 10's push-plus-reconcile and Lesson 9's priority queues apply directly: push the new highest bid to watchers over a persistent connection, order updates by a version so late messages do not overwrite newer ones, and have clients re-fetch on reconnect. See real-time updates.
URL shortener (bit.ly): unique short codes and fast redirects. Two classic choices are a hash of the long URL or a counter. For a hash, first canonicalise the URL (lowercase the host, remove default ports, normalise trailing slashes) so equivalent URLs map to one code, then hash (SHA-256), encode in base62 (letters and digits, no plus or slash, so it is URL-safe) and take the first 8 characters, giving 62^8 ≈ 218 trillion codes. Collisions are possible, so a UNIQUE constraint and a few retries with a salt are needed. For a counter, Redis INCR is atomic because Redis runs commands on one thread; base62 of one billion is only 6 characters. Sequential codes are guessable, so mix the counter with a secret (for example XOR or a keyed permutation) before encoding. Redirects at 100 million daily users × 5 redirects is about 5,800 a second on average, perhaps 100 times that at peaks; a B-tree index on the code serves lookups in O(log n), and a Redis cache in front (memory reads around 100 ns versus SSD around 0.1 ms) absorbs the peaks. A billion rows of about 500 bytes is 500 GB, so one Postgres primary with replicas is enough. Razorpay's posts touch the same tools: Splitz uses MurmurHash for uniform, deterministic bucketing, counters in Nginx's rate limiter are atomic increments with TTLs, and the ID problems are covered in unique ID generation.
Pastebin: tracking page analytics. The primer's answer is batch: analytics need not be real time, so run MapReduce over web-server logs, emitting a key of (month, URL) with a count of 1 and summing in the reducer. At 10 million pastes a month and a 10:1 read ratio, batch is plenty. Razorpay's facts started exactly like this, daily batch rebuilds, and moved to streaming only when merchants needed fresher reports (Lessons 11 to 13). The lesson: start with batch and move to streaming when freshness becomes a product requirement.
Numbers to know: over-engineering for write throughput. A common interview mistake is to add Kafka, sharding and caches for write rates that one database handles easily. Razorpay's numbers make the point: the notification service peaked around 1,000 to 2,000 events a second and flash sales around 1,500 requests a second. A single well-tuned MySQL primary handles several thousand simple writes a second. Razorpay's problems were not raw write throughput. They were connection counts (ProxySQL), IOPS coupling (Kinesis between workers and the database), slow dependencies (bank latency) and contention on hot rows (balance locks). Before scaling writes, ask what actually saturates first. See back-of-the-envelope estimation.
| Interview step | Razorpay-flavoured answer |
|---|---|
| Requirements | Name partner failure, burst traffic and exactness of money as first-class requirements |
| Estimation | Peak = about 10 times daily average for 10 minutes; bank latency up to 20 s; size connections with Little's law |
| High-level design | API, router, gateway adapters, ledger with outbox, event stream, detector, notifier |
| Data model | Payment state machine, balance plus transaction log, outbox table, facts in a lake |
| Deep dive 1 | Downtime detection on streams with dynamic windows |
| Deep dive 2 | Correctness: lock ordering, idempotent outbox tasks, reconciliation |
| Scaling | Pools, rate limits per merchant and route, priority queues, pre-scaling |
| Operations | Alerts as code, command center, timeline-based RCAs |
When to Use It#
Study Razorpay's posts, and borrow their patterns, when:
- Your product depends on partners you do not control: banks, carriers, cloud APIs, logistics providers or LLM vendors. Downtime detection per cohort and success-based routing apply to any multi-provider integration.
- Traffic arrives in predictable bursts: sports events, sales, payroll days, ticket drops. Pre-scaling, per-tenant rate limits and connection pooling are the playbook.
- Correctness of money or inventory matters more than latency: outbox writes, consistent lock ordering and reconciliation jobs are the habits.
- You run a shared platform for many teams: ownership tags, alerts as code, self-service experiments and a command center scale the human side.
- You need fresh, wide reports over mutable data: the streaming facts design shows the real cost of incremental denormalisation.
When NOT to Use It#
- A single provider with a strong SLA and low volume. Building ML routing for one gateway and 50 payments a day is waste. A timeout, a retry and a status page are enough.
- Fresh data is not a requirement. If reports can be a day old, keep the daily batch. It is simpler and correct by construction (compare the pastebin analytics answer).
- Few teams and few services. A command center, alert GitOps and an in-house tracing stack make sense at dozens of services and hundreds of engineers (the tracing post's own rule 4), not at five.
- Strong ordering across tasks. A polling outbox without per-key ordering is the wrong tool if consumers need strict order; use CDC into a partitioned log instead.
- Latency budgets that cannot absorb a sidecar. For a hot path measured in single-digit milliseconds, a full mesh may cost too much; consider library-level TLS or node-level proxies.
How to Implement It#
A minimal path to Razorpay-style reliability for a multi-provider payment system:
- Model the matrix. List every method, provider and issuer combination as a cohort. Emit a status event per payment with those dimensions.
- Stream status events into Kafka and compute success rates per cohort in a stream processor, with count windows for small cohorts and time windows for large ones, hysteresis and a moratorium for short dips.
- Publish downtimes to the router, checkout and merchants. Exclude providers under downtime and rank the rest by recent success, with a small exploration share.
- Protect shared resources: a connection pool between app and database, rate limits per tenant and route at the edge, separate queues per priority, and per-customer isolation for outbound calls.
- Make every multi-system write local and atomic with an outbox; make every task idempotent; reconcile balances and counts daily.
- Take a lock order and enforce it in code review and tests; surface every database error code; never continue after a failed transaction.
- Load-test before every peak with real integrations where timing matters, mocks elsewhere, and profiling at each step. Verify each metric from a second source.
- Run alerts as code with required owner tags, and automate incident logistics. Staff a communication role separate from the fixers. Write RCAs with a timeline of Event, Action, Missing and Missed.
# Handbook illustration: one config that ties the pieces together
downtime_rules:
- cohort: { method: netbanking, bank: HDFC }
window: { type: count, size: 100 }
open_below: 0.60
close_above: 0.70
moratorium_seconds: 60
severity: high
routing:
exclude_on_downtime: true
exploration_share: 0.03
rate_limits:
- key: merchant_route
window_seconds: 1
limit: 200
notifications:
queues: [P0, P1, P2]
slow_customer_demote_after_seconds: 300
outbox:
max_attempts: 10
backoff: exponential
reconciliation:
balances: daily
webhooks_from_vendor: every_3_hoursTechnology choices.
| Need | Razorpay choice | Alternatives | When each fits |
|---|---|---|---|
| Stream detection | Flink with broadcast rules and custom windows | Kafka Streams, Spark Structured Streaming | Flink for low-latency stateful logic; Kafka Streams for JVM services without a cluster; Spark when the team already runs micro-batch |
| Dual writes | Outboxer library on MySQL | Debezium CDC to Kafka, two-phase commit | Polling outbox for simple, low-volume tasks; CDC for ordering and fan-out; 2PC almost never across services |
| DB connection pooling | ProxySQL sidecar | PgBouncer for Postgres, RDS Proxy, app-level pools | Sidecar for small blast radius; central proxy for fewer moving parts; app pools for runtimes that support them |
| Rate limiting | Nginx sidecar, fixed window | Token bucket in Redis, Envoy rate limit service | Fixed window for simplicity at second granularity; token bucket for smooth bursts; Envoy when already on a mesh |
| Leader election | Consul sessions and KV | etcd leases, ZooKeeper ephemeral nodes, Kubernetes Lease | Use whatever consensus store you already operate |
| Async delivery | SQS plus Kinesis | Kafka, RabbitMQ | Managed queues for simplicity on AWS; Kafka for replay and high fan-out |
| Lakehouse table | Delta Lake on S3 | Apache Hudi, Apache Iceberg | Delta with Spark and Databricks; Hudi for record-level upsert focus; Iceberg for engine-neutral tables |
| Interactive SQL | Trino plus Alluxio | Presto, Spark SQL, a warehouse such as Snowflake or BigQuery | Trino for open lakes; a warehouse when you prefer managed over control |
| Metrics | VictoriaMetrics with vmagent | Prometheus plus Thanos, Cortex, Mimir, managed services | VictoriaMetrics for simplicity and cost; Thanos or Mimir for object-storage-first designs |
| Tracing | Jaeger with OpenCensus SDKs | OpenTelemetry Collector with Tempo, SaaS APM | Self-hosted for compliance and long history; SaaS for speed of adoption |
| Experiments | Splitz with MurmurHash and RedisBloom | LaunchDarkly, Unleash, GrowthBook | Build when scale and data residency demand it; buy otherwise |
| Service encryption | Istio mTLS | Linkerd, app-level TLS, cloud-native options | Istio for rich policy; Linkerd for simpler, lighter meshes |
Trade-offs#
| Choice Razorpay made | What it bought | What it cost |
|---|---|---|
| Stream-based downtime detection | Low MTTD, independence from the main DB | A new technology, custom windows, two jobs to run |
| ML routing | Plus 60 percent SR in bursts, no manual work | Model upkeep, less explainability, exploration cost |
| Polling outbox without a broker | Atomicity with almost no infrastructure | Delay, no ordering, DB load |
| Consistent lock order | No deadlocks between the two flows | A rule every developer must follow |
| Consul leases for leadership | No custom consensus | Failover delay up to TTL plus lock delay; no fencing by default |
| ProxySQL as a sidecar | Small blast radius, no network hop | Slower deploys, shutdown ordering, ALTER workarounds |
| Fixed-window rate limiting | One atomic counter, cheap and fast | Up to 2x bursts at window edges |
| Pre-scaling before matches | Capacity ready before bursts | Paying for idle capacity |
| Kinesis between workers and DB | Worker scaling free of IOPS limits | Lagging records, another stream to run |
| Push webhooks plus reconcile | Seconds of latency, 20x fewer API calls | Vendor-hosted code, two paths |
| Streaming facts on Delta | Freshness under an hour | Complex engine, tuning, backfills |
| Self-managed Trino and Alluxio | Control over cost, latency and availability | Platform team effort |
| VictoriaMetrics | About 18 dollars a day versus about 400 | Shorter default retention, smaller ecosystem |
| 10 percent trace sampling | 1 TB a day instead of 8 | Missing most successful traces |
| Command center and timeline RCAs | Faster recovery, clearer communication | Headcount and process |
| Strict frontend pipeline | 350x fewer crashes | Slower PRs and deploys |
| Bloom filter segments | 3 MB per million IDs | Rare false positives |
| Istio mTLS | Uniform encryption and identity | About 20 percent latency, sidecar resources |
Common Pitfalls#
- Monitoring from inside the thing you monitor. The first downtime detector died with the payment system. Run detectors on separate infrastructure and data paths.
- Trusting a lock you did not verify. A hidden driver bug turned FOR UPDATE into a plain read. Check every error and reconcile invariants.
- Counting pending as failed. Payment methods with delayed outcomes will trip naive SR thresholds.
- Retrying without backoff or budget. The perf-test internal DDoS turned 4x load into 6x. Every client needs timeouts, backoff with jitter and a retry cap.
- Believing dashboards blindly. Two wrong panels (memory and CPU) sent the perf team the wrong way. Cross-check with a second source.
- Scaling the database to fix a coupling problem. Vertical scaling bought the notification service time, not a solution.
- Letting label cardinality grow freely. One label can multiply series a thousandfold.
- Writing RCAs that explain the failure but not the recovery. Most of the incident's time is often in detection, engagement and diagnosis.
- Leaving a mesh in PERMISSIVE. It is a migration step, not a security posture.
Real-World Examples#
- Razorpay itself, as described in each lesson: downtime detection on Flink, ML routing, Outboxer, ProxySQL and Nginx sidecars for IPL, VictoriaMetrics, Jaeger, Splitz and Istio.
- Swiggy solves the same payment-routing problem from the merchant side, with explore-exploit routing across gateways; see Swiggy engineering.
- Stripe writes about idempotency keys, rate limiters and ledger correctness; see Stripe engineering.
- Zerodha shows a different Indian fintech approach, with a small team, simple tools and strict cost control; see Zerodha engineering.
- AWS Builders' Library explains the theory behind many of these fixes, including timeouts, retries with jitter and shuffle sharding; see AWS Builders' Library.
- Uber and Netflix show stream processing and observability at larger scale; see Uber engineering and Netflix engineering.
In the Interview#
Deep Dive: designing a small payment gateway with Razorpay's lessonsShow
Prompt. Design a payment gateway for 2,000 merchants with 2 million payments a day, peaking at 10x average during evening events, across three acquiring gateways and four methods.
Estimates (handbook's illustration). Average 2,000,000 / 86,400 ≈ 23 payments a second; burst 230 a second for 10 minutes. Bank latency median 2 s, P99 20 s. By Little's law, in-flight payments at burst with a 3 s mean are about 700. Database time per payment about 15 ms across 6 queries gives about 3.5 busy connections at burst, so a pool of 50 is generous. Without pooling, 700 or more connections would be pinned by bank waits.
Components.
- API with idempotency keys and per-merchant rate limits (fixed one-second windows).
- Payment state machine in MySQL or Postgres: created, authorised, captured, failed, refunded, with transitions in transactions.
- Outbox in the same database for webhooks, ledger postings and analytics events, drained by idempotent workers.
- Router with three gateway adapters, circuit breakers per adapter, downtime exclusions and success-based ranking.
- Detector: a small Flink or Kafka Streams job over status events, with cohorts per method and gateway, count windows of 50 for small cohorts, hysteresis and a 60-second moratorium.
- Notifier: P0 and P1 queues, per-merchant concurrency caps, exponential retries for 24 hours.
- Ledger: append-only entries; balances derived and cached with a version; daily reconciliation against gateway settlement files.
- Observability: RED metrics per route, SR per cohort, traces with 2xx sampling, alerts as code.
Failure walk-through. Gateway B's UPI success falls from 85 to 30 percent at 19:02. The detector's count window fills in about 15 seconds and opens a downtime at 19:02:20. The router excludes B for UPI; success returns to normal for new payments. Payments already sent to B stay pending; a status poller resolves them as the bank recovers, and the outbox sends webhooks when they settle. The alert pages the payments on-call with the cohort in the title. The timeline RCA asks why detection took 20 seconds and whether the moratorium was right.
What you would sacrifice. A second gateway contract and its fees, slightly stale routing scores, at-least-once webhooks that merchants must deduplicate, and a daily rather than real-time reconciliation.
Key Takeaways#
- Partner failure is the normal case for payments. Design detection, routing and customer communication for it from day one.
- Detect from symptoms that customers feel, such as success rate per cohort, on a stream, with statistics that respect small samples.
- Protect shared resources from slow dependencies with pools, rate limits, priority queues and per-customer isolation.
- Make cross-system writes atomic locally with an outbox, make tasks idempotent, keep a global lock order, and reconcile invariants.
- Prepare for known peaks by pre-scaling and testing, because autoscaling and debugging both take longer than a burst.
- Fresh analytics over mutable data is a hard problem: incremental denormalisation needs dependency graphs, caches and careful file layout.
- Observability is a journey: logs, then metrics, then traces, choosing simple, open and cheap tools and controlling cardinality.
- Incident response is a system: alerts with owners, automated logistics, a communications role, and RCAs that study recovery as well as cause.