Skip to content

Zerodha Tech: Small Teams, Huge Financial Workloads

Advanced 131 min read Part 18 of 18

How a 30-person team runs India's largest stockbroker on self-hosted Go, Postgres and Redis: scaling with common sense, boring tech and its trade-offs.

Summary#

Zerodha is an Indian stockbroker. Since January 2019 it has been the largest broker in India by active clients, and it handles roughly 15 to 20 percent of the country's retail trading volume. On busy days its platform processes millions of trades. At market open it streams millions of price ticks per second to hundreds of thousands of connected users. Postgres tables at Zerodha hold hundreds of billions of rows. The company never raised outside funding, has no marketing team and is profitable. The technology behind it was built by a team of about 30 people for most of its history.

Zerodha's engineering blog (zerodha.tech) explains how that is possible. The posts do not describe exotic infrastructure. They describe ordinary tools used carefully. Go runs the hot paths. Postgres and Redis hold the data. HAProxy and Nginx sit at the edge. Almost everything is self-hosted free and open-source software (FOSS). Throughout, the team is disciplined about measuring, simplifying and rewriting.

This page studies the Zerodha posts in seven families:

  • Philosophy and stack: how the tech team was formed, the full stack, and being future-ready with common sense.
  • Scaling with common sense: the sixteen-point essay on code quality, databases, connection pools, latency, caching, allocation, concurrency and vertical scaling, contrasted with the classic "scale to millions on AWS" ladder.
  • Data: Postgres with hundreds of billions of rows, sharding by financial year with foreign data wrappers, the sql-jobber (now dungbeetle) report cache, and Blobasaur, a SQLite-backed blob store that speaks the Redis protocol.
  • Batch at deadline: generating, signing and emailing 1.5 million PDFs in 25 minutes on an ephemeral Nomad cluster, including a run-in with S3's per-prefix rate limits.
  • Observability on a budget: replacing ELK with Vector, ClickHouse and Metabase, and monitoring a hybrid data-centre and AWS estate with Prometheus and VictoriaMetrics.
  • Rules and clients: the Veto risk-rule engine's move from an expression language to compiled Go plugins, and the mobile journey from native to React Native to Flutter.
  • Platform, product and people: Kite Connect, Kafka as a decoupling bus, open-source projects, the Alar dictionary, user disengagement by design and remote work.

A final family pulls the lessons together into the trade-offs of boring technology.

Why It Exists#

Most system design material assumes that scale requires a large team, a cloud-native platform and many managed services. Zerodha is a counter-example worth studying because its constraints are harsh and its means are modest:

  • The workload is spiky and synchronous. Indian equity markets open at 9:15 and close at 15:30 IST. A large share of the day's orders and logins arrive in the first minutes after the open. Traffic can jump about tenfold within ten seconds, then fall away after the close. There is no "spread the load over the day".
  • Correctness is regulated. A broker answers to the Securities and Exchange Board of India (SEBI) and the exchanges. Contract notes must reach every trader before the next session. Logs must be retained for years. New rules can arrive with a few weeks' notice.
  • Latency is visible. Traders watch prices tick. A 10 ms regression or an extra 50 KB of JavaScript is treated as a defect, not a tolerance.
  • The team is tiny. About 30 engineers, with no product managers, built and ran the trading platform (Kite), the back office (Console), mobile apps, internal tools and the data platform.
  • Money is finite by choice. With no outside funding and no marketing budget, every recurring cost matters, including SaaS fees that scale per seat.

The textbook pages (PostgreSQL, Redis, observability, choosing technologies) explain the tools. Zerodha's posts show how far those tools go when a small team understands them deeply, and what that choice costs.

For each post the page asks:

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

Where this page adds its own example numbers to make an idea concrete, they are marked "(handbook's illustration)". All other numbers come from the posts and are as of each post's date.

How It Works#

The diagram shows where each family sits in a trading day. Clients (the Kite web app, the Flutter mobile apps and third-party apps on Kite Connect) reach Zerodha through HAProxy and Nginx. Orders pass the Veto risk checks before reaching the order management system (OMS) that talks to the exchanges over leased lines in physical racks. The ticker streams market data over WebSockets. Reads come from a hot Redis cache. Console, the back office, runs reports from Postgres through a report cache. At night, end-of-day (EOD) jobs import the day's trades, and an ephemeral cluster generates and emails contract notes. Logs and metrics flow into ClickHouse and VictoriaMetrics, and Kafka connects systems without direct API calls.

The lessons follow the families in order. Each covers one post, or a few closely linked posts, and ends with what the design gave up.

Family 1: Philosophy, team and stack

Lesson 1: Hello, World: how a 30-person team runs a broker (2020)#

Assumptions. The first post, by CTO Kailash Nadh, introduces the tech team. Its assumptions are about people as much as machines:

  • Traffic. About a million daily active users and more than seven million trades on a record day in early 2020. For comparison, the post notes that Charles Schwab's record was about 2.7 million. More than a billion trades a year, hundreds of thousands of HTTP requests per second at peak, and around 16 million market ticks per second fanned out to hundreds of thousands of concurrent clients.
  • Latency. Traders feel every millisecond. The quality bar is concrete: nobody gets to add an extra 50 KB of JavaScript or a 10 ms latency spike without a reason.
  • Consistency. Orders, positions and money must be exact. Market-data views can be a few hundred milliseconds behind.
  • Maintenance. A small team that owns everything it runs. No vendor to call at 9:14 in the morning.

The story. Zerodha was founded in 2010 by Nithin and Nikhil Kamath. The tech team only formed in mid-2013, when the company already had about 75 employees and used vendor software. By 2020 the company had about 1,200 employees, and the tech team was about 30. That 30 included 2 mobile developers, 2 designers, 2 frontend developers, 1 test engineer, 1 DevOps engineer and 1 liaison with the business. Everyone else was a full-stack developer. Nobody on the team came from finance. There are no product managers. Small micro-teams of two to four people own a product end to end, from database to user interface.

The stack in 2020.

  • Languages. Go for hot paths: the Kite API, the ticker and the order pipeline. Python with Django and Flask for back-office tools. A little C++ and Java where a library required them. ERPNext (a Python ERP framework) for internal business processes.
  • Frontend. Vue, after an earlier Angular version. Flutter on mobile, with one React Native app remaining.
  • Data. Self-managed Postgres, plus MySQL with billions of rows in older systems, and Redis everywhere.
  • Edge and bus. HAProxy and Nginx at the edge. Kafka as the organisation-wide message bus.
  • Self-hosted tools. GitLab for code and CI, Rundeck for operations jobs, RocketChat for chat, Metabase for dashboards, Phabricator and Postal for email. Kubernetes was being explored, mainly to make deployments uniform.
  • Observability. Sentry, Grafana and Prometheus, with ELK holding logs that regulation requires to be kept for years.
  • Infrastructure. Hybrid: physical racks in data centres where the exchange leased lines terminate, plus AWS for everything that does not need to be next to the exchange.

The principles.

  • FOSS first. Prefer open-source software, and self-host it.
  • Zero trust for internal tools. Every internal tool sits behind a single sign-on layer with OAuth and two-factor authentication. SSH uses short-lived certificates instead of shared keys.
  • Technical decisions are made by technical people. No managers choose databases.
  • Rewrite when needed, and freeze features to do it. A rewrite is a normal tool, not a crisis.
  • Treat the organisation like modular software. Teams have clear interfaces and few dependencies.

That last principle paid off on 12 March 2020. Zerodha moved the whole company to remote work overnight because the access model was already zero trust. It also made it natural to open the platform to outside developers ("Broking as a Platform", Lesson 20) and to fund fintech start-ups through Rainmatter.

Overlooked constraints.

  • Hiring for generalists is slow. A team of full-stack owners works only if every hire can handle a database, a Go service and a Vue page. Such people are rare, so headcount grows slowly by design.
  • No PMs means engineers must say no. The business asks for features through a liaison. Without someone filtering, a small team drowns. Lesson 3 explains how the team pushes back.
  • Hybrid infrastructure is not optional. Exchange connectivity needs physical presence. A "cloud only" design is not available to a broker, however much simpler it would be.

What Zerodha sacrificed. Breadth and speed of new features. A 30-person team cannot ship many products in parallel. Zerodha accepted a narrower product surface and slower feature velocity in exchange for depth, low cost and ownership. It also gave up the safety net of vendor support for the tools it self-hosts.

Deep Dive: what 30 engineers per billion trades meansShow

Trades per engineer (handbook's illustration). A billion trades a year handled by 30 engineers is about 33 million trades per engineer per year. A typical large-bank technology division may have thousands of engineers for a comparable or smaller retail volume. The ratio is not a fair productivity measure, because banks run many more products and regulatory systems. It still shows how much a narrow scope and a simple stack reduce coordination cost.

Coordination cost. In a team of n people who all talk to each other, there are n(n minus 1) divided by 2 communication paths. For 30 people that is 435 paths. For 300 it is 44,850. Micro-teams of 2 to 4 with clear interfaces reduce the paths that matter. Each team talks mostly within itself and through a few stable APIs. That is the organisational version of loose coupling, and it is why the post compares the org chart to modular software.

Ticks per second. 16 million ticks per second spread over hundreds of thousands of clients sounds impossible until you notice that each client subscribes to a few dozen instruments. If 300,000 clients each watch 50 instruments, each updating a few times a second, the server sends roughly 300,000 × 50 × 1 = 15 million messages per second (handbook's illustration). The ticker's job is fan-out of small binary packets, which a Go process with one goroutine per connection and pre-encoded packets can do on a handful of large machines.

Lesson 2: The stack, all self-hosted (stack page)#

Assumptions. Zerodha publishes its stack openly. The list assumes that each component will be run by the same small team, so it must be operable by a generalist. It also assumes that any SaaS priced per seat or per request becomes expensive when the company has more than a thousand staff and millions of users.

The stack by layer. As listed on the stack page:

  • Languages: Go, Python, Java, JavaScript and Dart.
  • Databases: PostgreSQL, ClickHouse, Redis, SSDB, ScyllaDB, DuckDB and MySQL.
  • Proxies and gateways: Nginx, HAProxy and Kong.
  • Streams: NATS, Kafka, Redpanda Console (a Kafka UI) and Benthos (a stream processor).
  • Observability: Vector, Grafana, VictoriaMetrics, Alertmanager and Sentry.
  • DevOps: Rundeck, GitLab, Airflow, Salt, GLPI (IT asset management), Nomad and Fastlane (mobile release automation).
  • Web and mobile: Vue, Django, Frappe, Flask and Flutter.
  • Email: Haraka and Postal (mail servers), Maddy and Listmonk (Zerodha's own newsletter manager).
  • Business tools: OSTicket, ERPNext, NextCloud, Vaultwarden, Metabase and Matomo (self-hosted web analytics).
  • Communication and docs: Mattermost and Discourse; MkDocs and Outline.
  • Infrastructure and other: Ubuntu, Netbird (a WireGuard-based mesh VPN), Cypress for tests, pandas, GraphQL, PaddleOCR, CFSSL (Cloudflare's PKI toolkit) and Athens (a Go module proxy).
  • CMS: WordPress, Hugo and Zola.
  • Security monitoring (SIEM): Wazuh and DFIR-IRIS.

Reading the list as a designer. Four patterns stand out.

  • One tool per job, mostly. Postgres is the default database. ClickHouse is used for analytical and log data, Redis for caches and ephemeral state, DuckDB for local analytics. There are overlaps (MySQL, SSDB, ScyllaDB), and the posts show these are either legacy or under replacement (SSDB by Blobasaur in Lesson 12).
  • Small, single-binary tools are preferred. Nomad over Kubernetes for batch (Lesson 15), VictoriaMetrics over Thanos (Lesson 17), Vector over Logstash (Lesson 16), Haraka over Postal (Lesson 15). Each choice reduces the number of moving parts a generalist must understand.
  • Business software is self-hosted too. Ticketing, CRM, ERP, password management and file sharing are all FOSS. Lesson 3 shows the cost arithmetic.
  • Security is layered on every tool. Netbird and SSO put every internal tool behind identity, so self-hosting does not mean exposing dozens of admin panels to the Internet.

Overlooked constraints.

  • Upgrades are now your job. Dozens of self-hosted tools each need patching, backup and occasional migration. The team must treat these as routine work, not an afterthought.
  • Breadth needs depth. A list this long is safe only if each tool is simple enough to understand from the inside. That is why single binaries keep winning.
  • Security patches arrive at awkward times. A critical CVE in a self-hosted tool is the team's emergency, not a vendor's.

What Zerodha sacrificed. Convenience and polish. A managed service often has better UI, faster feature releases and someone else on call. Zerodha traded those for control over data, predictable cost and freedom from vendor lock-in. It also accepted that some tools (Metabase as a log viewer, for example, in Lesson 16) are less pleasant than a commercial equivalent.

Lesson 3: Being future-ready with common sense (2021)#

Assumptions. Written a year after the 2020 trading boom, this post assumes constant change. Trades grew from about 2 million a day in January 2020 to more than 7 million in April 2020 and more than 12 million by mid-2021. Users grew from about 2 million to more than 6 million. The team grew from 30 to 31. The post assumes that regulators can change rules with very little notice, that frameworks will come and go, and that the team will not grow much.

The main ideas.

  • Concepts change slowly; implementations change fast. CGI scripts and serverless functions are the same idea (run code per request) in different clothes. Server-side rendering returned after a decade of single-page apps. Learn the concepts and treat specific tools as replaceable. When Flutter was still in alpha in 2018, the team bet on it only after a two-week prototype proved the concept (Lesson 19).
  • Pragmatism over purity. In mid-2020 SEBI gave brokers about four weeks to add a new depository authorisation step (a TPIN) before clients could sell shares. Then it added an SMS OTP flow, and later changed the validity rules. A system that needs a quarter to change one flow cannot survive that. Pragmatism means shipping a correct, simple version fast and improving it later.
  • Stable interfaces, internal APIs included. Internal APIs deserve the same care as public ones, because they are what lets one micro-team change its internals without breaking another. The post stresses that modularity does not require microservices. A well-structured monolith with clean module boundaries is modular.
  • Clever software, dumb code. The product can be clever, but the code should be obvious. Code review flags clever tricks. Comments explain why, not what.
  • Estimation is hard. Admit it, and prefer small steps that can be measured.
  • Slow down to speed up. Rewrites and feature freezes are investments (detailed below).
  • Beware non-technical "tech leaders". People who choose technology without understanding it create the "IT-vendor spider web" seen at many large institutions. The post describes a bank whose developers never actually write code; they only manage vendors.
  • Abstraction and saying no. Most business software is CRUD (create, read, update, delete) underneath. Teams should bring problem statements, not solutions ("we need a microservice that..."). Engineers then find the simplest abstraction, which often means saying no to the proposed implementation.

Slow down to speed up, in numbers. The post's rewrite history:

  • Kite, the trading platform, launched in Python in 2015 for about 1,000 users. v2 came in 2016. v3 in 2017 was rewritten in Go and now serves more than a million concurrent users. A 2021 rewrite of the Kite backend had about 50 percent fewer lines of code than the one it replaced.
  • The web frontend moved from Angular to Vue.
  • Mobile went native, then React Native, then Flutter.
  • The ticker was rewritten more than five times in six years. Its internal transport moved from custom TCP, to ZeroMQ, to Nanomsg and its Go port Mangos, then to NATS.
  • Console, the back office, moved from Python to Go, with ClickHouse experiments for analytics.
  • Latency budget. Through all of this the client round trip stayed around a 40 ms baseline.

How rewrites are done safely. Feature freezes give a team weeks without new requests. Partial blue-green deployments run old and new versions side by side for months, routing a growing fraction of users to the new one. Technical debt is paid on purpose, and fear of rewriting is treated as a smell.

Connect by disconnecting. Systems used to call each other's APIs directly, a "maze" where every new consumer added a dependency. Zerodha replaced much of it with Kafka publish-subscribe. A source-of-truth system publishes standardised events to a topic. Any team can attach a small sidecar consumer to react. Example: when an account is deactivated, the accounts system publishes one event, and a mailing-list sidecar unsubscribes the user instantly. The accounts team does not need to know the mailing system exists. The post describes the result as near-zero maintenance. See pub-sub and event streaming.

Self-hosting and cost. Self-hosted tools include Postgres, MySQL, ClickHouse, Redis, Kafka, ELK, Sentry, Grafana, GitLab, ERPNext, Metabase, Discourse, and zero-trust access plus VPN. Two cost examples from the post:

  • Ticketing. OSTicket plus ERPNext costs under 10,000 dollars a year. A SaaS ticketing quote for the same staff count was over a million dollars a year.
  • CRM. A CRM built on Frappe costs a few thousand dollars a year, against SaaS quotes in the millions.

Zerodha liked Frappe enough to invest in the company behind it in 2020. Because SSO, 2FA and VPN had been in place since 2017, Zerodha met SEBI's 2018 cybersecurity rules on day one. Its 2020 remote switch was also painless.

Systems go down. The post ends by admitting that failures happen anyway. Corporate actions (splits, bonuses and mergers that change positions overnight) are tricky. In April 2020 crude oil futures settled at a negative price, which broke assumptions in many systems worldwide. EOD processing needs timing leeway for late exchange files.

Overlooked constraints.

  • Rewrites need an owner who stays. A rewrite by people who will not maintain it creates a new legacy system. Zerodha's micro-teams own what they rewrite.
  • Kafka decoupling moves complexity into schemas. Standardised topics only work if event schemas are versioned and stable. Otherwise the maze returns as a schema maze.
  • Self-hosting savings assume competent operators. The million-dollar saving is real only because the team can run ERPNext and OSTicket reliably. A team that cannot will pay in outages instead.

What Zerodha sacrificed. Feature velocity during freezes, and the comfort of incremental change. Planned rewrites mean periods where the business waits. Event-driven decoupling sacrifices immediate consistency between systems: the mailing list unsubscribes a moment after deactivation, not in the same transaction.

Deep Dive: the arithmetic of self-hosting versus SaaSShow

Per-seat pricing (handbook's illustration). A SaaS helpdesk at 100 dollars per agent per month for 800 support and operations staff is 960,000 dollars a year, close to the post's "over a million" quote. A self-hosted OSTicket and ERPNext setup needs a few servers, say 4 instances at 300 dollars a month, which is about 14,400 dollars a year. Add maintenance, perhaps 10 percent of one engineer at 60,000 dollars a year, which is 6,000 dollars. The total of about 20,000 dollars is about 50 times cheaper.

When the arithmetic flips. For a 20-person company, the same SaaS costs 24,000 dollars a year. Self-hosting still needs that 10 percent of an engineer plus servers, about 20,000 dollars. The saving disappears, and the company takes on risk. Self-hosting wins when seats or volume are large and the team already has strong operations skills. Zerodha had both.

Hidden SaaS costs Zerodha avoided. Data residency and regulator audits are simpler when data never leaves your infrastructure. There is no price increase at renewal. There is no forced migration when a vendor is acquired.

Hidden self-hosting costs Zerodha accepted. Backups and restore drills for every tool. Upgrade testing. Security patching. An engineer being woken for a ticketing outage.

Family 2: Scaling with common sense

The 2020 essay "Scaling with common sense" is a list of sixteen points. Lessons 4 to 8 group them by theme and add the numbers behind each one.

Lesson 4: Good code, simple stacks and the database bottleneck (2020)#

Assumptions. The essay assumes an ordinary web workload: HTTP APIs in front of a relational database, read-heavy, with bursts. It assumes the team controls its own code, so the cheapest fix is usually in the code, not in the infrastructure. And it assumes comparisons between companies ("we handle X requests per second") are meaningless without context. The essay jokes that "97.42 percent" of scaling advice is irrelevant to any given system.

Point 1: comparisons are meaningless. A request at one company may be a cached lookup; at another it may be a ten-table join. Request rates without request cost tell you nothing.

Point 2: scaling starts with good code. The post's example is a Python service that costs 100 dollars a month to run, which after a rewrite with better queries and less work per request costs 25 dollars. That is a fourfold saving from code alone, before any architecture change. Poorly written code multiplies every later cost: more servers, more cache, more database load.

Point 3: avoid premature optimisation. Do not build for a scale you do not have. Measure first, then optimise the part that is actually slow.

Point 4: KISS (keep it simple). "Boring" beats "cool". A bash script that deploys with rsync is fine if it works. Zerodha adopted Kubernetes not because it scales better but because it gave uniform deployments across teams. Each new technology must earn its place by solving a problem the team actually has.

Point 5: the bottleneck is almost always the database. A web framework that benchmarks at 500,000 requests per second, sitting in front of a database that can do 1,000 queries per second, serves 1,000 requests per second. Choosing the fastest framework does nothing if every request waits on the database. Optimise the slowest component first.

Point 6: an RDBMS almost always works. Zerodha runs Postgres with a replica holding hundreds of billions of rows. A relational database with good schema design handles far more than most teams assume. See relational databases and SQL vs NoSQL.

Point 7: everyone forgets to index. The post gives an order of fixes for a slow database:

  1. Schema. Is the data modelled sensibly for the queries?
  2. Indexes. Does every frequent filter and sort have a supporting index?
  3. Query plans. Use EXPLAIN (and EXPLAIN ANALYZE) to see what the planner actually does.
  4. Configuration. Only then tune memory and connection settings.

Specific traps the post calls out:

  • ORMs hide bad queries. An ORM that issues N queries in a loop (the "N+1 problem") or selects every column turns a fast page into a slow one.
  • Composite index column order matters. An index on (user_id, created_at) helps "WHERE user_id = ? ORDER BY created_at" but not "WHERE created_at > ?" alone.
  • Use enums or small integers for low-cardinality text. They are smaller to store, index and compare.
  • LIKE '%term%' cannot use a normal B-tree index. Leading wildcards force a full scan. Use a trigram or full-text index, or a search engine. See database indexing.

Point 8: fewer queries. Combine lookups with joins and common table expressions (CTEs) instead of many round trips. Batch writes: one INSERT of 1,000 rows is much cheaper than 1,000 INSERTs. The post cites WordPress plugins that issue dozens or hundreds of queries per page as the counter-example.

Overlooked constraints.

  • Indexes cost writes. Every index slows inserts and updates and takes disk. Zerodha's Postgres post (Lesson 9) warns against over-indexing for that reason.
  • "The database is the bottleneck" assumes a database on the path. Systems that read from a pre-built cache (Lesson 6) move the bottleneck to the cache-filling job instead.
  • Simple is not the same as easy. A plain bash deploy is simple to read, but it must still handle failure, rollback and secrets correctly.

What Zerodha sacrificed. The ability to hire people who only know frameworks and ORMs. This style of scaling needs engineers who read query plans and understand the database. Zerodha also gave up some convenience features of heavy frameworks in exchange for control.

Deep Dive: index order, selectivity and a worked EXPLAINShow

Composite index order. A B-tree index on columns (a, b) is sorted by a, then by b within each a. It can answer:

  • "a = x" (jump to the x section).
  • "a = x AND b > y" (jump to x, then scan forward from y).
  • "a = x ORDER BY b" (already sorted).

It cannot efficiently answer "b > y" alone, because b values are scattered across every a section. So put equality columns first and range or sort columns last.

Selectivity (handbook's illustration). A trades table has 2 billion rows, 5 million users and 3 years of dates. A query for one user's trades in one month must find about 2 billion ÷ 5 million ÷ 36 ≈ 11 rows.

  • Index on (user_id, trade_date): the planner jumps straight to those 11 rows. That is a few page reads, under a millisecond.
  • Index on trade_date only: one month holds about 55 million rows, and the planner must filter them by user. That takes seconds.
  • Index on user_id only: about 400 rows over 3 years must then be filtered by date. That is fast, but slower than the composite index.

Reading EXPLAIN ANALYZE. Look for "Seq Scan" on a big table where you expected "Index Scan". Look for large gaps between estimated and actual row counts, which mean stale statistics. Look for "Sort" nodes that spill to disk ("external merge"), which mean work_mem is too low for that query (Lesson 9). Fix the biggest node first.

Lesson 5: Network as little as possible: pools, latency and the Wild West (2020)#

Assumptions. Point 9 of the essay assumes that most time in a web request is spent waiting on the network: to the database, to the cache, to other services. It also assumes clients on the Internet are slow and unpredictable. Many Indian traders use mobile networks, sometimes on 3G.

9.1: Connection pooling, and why more connections do not help. A database with 10 worker processes can execute about 10 queries at a time. Opening 100 or 1,000 connections does not change that. The extra connections just queue inside the database and consume memory. Likewise, Redis processes commands one at a time per instance and can serve tens of thousands of requests per second on a single connection if you pipeline them. The rule follows: to send 10,000 requests to a backend, you need a pool of persistent (keep-alive) connections sized to the backend's real concurrency. That might be 100, or even 10, not 10,000.

The post then describes the failure mode. A pool of a few hundred connections can serve hundreds of thousands of requests per second only while latency stays constant. If backend latency rises, each connection is held longer, so callers open more connections. The extra connections overload the backend further, which raises latency again. This snowball can lock up a system, and the post calls it a kind of "deadlock". With traffic bursts of 10 times normal within 10 seconds at market open, this is not theoretical.

9.2: Latency is THE metric. The post's rule of thumb: one connection can carry one request per unit of latency. A connection with 1 ms latency serves 1,000 requests per second. At 10 ms, it serves 100 per second, so you need 10 connections or 10 copies of the service for the same throughput. This is Little's law: concurrency equals throughput times latency. It is why Zerodha cares so much about latency. Halving latency halves the connections, memory and servers needed. Redis is valuable partly because its lookups are O(1) and sub-millisecond.

9.3: The Internet is the Wild West. A client on a slow 3G link may take seconds to send a request or receive a response. If each client holds an application connection for that whole time, a few thousand slow clients exhaust the application. The solution is a reverse proxy (HAProxy, Nginx or an AWS ALB). The proxy juggles tens of thousands of slow client connections cheaply, buffers their requests and responses, and talks to the application over a small, fast pool of keep-alive connections. The application sees only quick, local requests. See proxies and reverse proxies and load balancing.

Overlooked constraints.

  • A fixed pool needs a queue policy. When all connections are busy, new requests must wait, fail fast or be shed. Unbounded waiting recreates the snowball inside the app. See resilience patterns.
  • The proxy is now a critical, stateful hop. It holds tens of thousands of client connections, so its memory, file descriptors and timeouts must be tuned and monitored.
  • Pipelining changes error handling. With many commands in flight on one Redis connection, a single connection failure affects all of them at once.

What Zerodha sacrificed. Elastic connection counts. A hard pool cap means that during a latency spike, some requests are rejected or delayed rather than served slowly. Zerodha prefers fast failure to a system-wide snowball. It also accepted another hop (the proxy) on every request.

Deep Dive: Little's law and sizing pools at market openShow

Little's law. For any stable system, L = λ × W. L is the average number of requests in the system (concurrency), λ is the arrival rate and W is the average time each request spends inside. It holds regardless of the arrival distribution.

Database pool (handbook's illustration). Suppose the Kite API needs 20,000 Postgres queries per second at the open, each taking 2 ms. Concurrency is 20,000 × 0.002 = 40 connections busy on average. Add about 50 percent headroom for variance and you get a pool of 60. If the database has 32 cores, 40 to 60 active queries is roughly the most it can run at once without thrashing. Opening 1,000 connections would add per-connection memory (Postgres forks a process per connection, typically several MB each) and context switching, with no extra throughput.

The snowball. Now latency rises to 20 ms because of a slow query. To sustain 20,000 queries per second you would need 400 connections. If the pool can grow to 400, the database gets 400 concurrent queries on 32 cores. Each query slows further, latency reaches 50 ms and demand rises to 1,000 connections. If instead the pool is capped at 60, throughput drops to 60 ÷ 0.02 = 3,000 queries per second. The other requests wait briefly or fail. The database recovers when the slow query ends. The cap turns a meltdown into partial degradation.

Slow clients. 50,000 mobile clients each taking 1 second to upload a request would need 50,000 application threads or goroutines if served directly. A proxy holds those 50,000 connections in a few hundred MB of memory with an event loop. It forwards each complete request in about 1 ms over its pool. The application then needs 50,000 per second × 0.001 s = 50 concurrent requests, a thousandfold reduction.

Lesson 6: Caching is almost a silver bullet (2020)#

Assumptions. Point 10 assumes that most reads in a trading app are for the current day's data: today's orders, positions, holdings and funds. Older history is rare and goes to Console. It assumes a user's data changes only when they act (place an order) or when the system processes an event (a trade fill). Between those events, the same read returns the same bytes.

How Kite reads. All data that Kite's API serves comes from a hot Redis cache, not from the database. An asynchronous service fills the cache with pre-serialised JSON bytes for each user and resource. When a request arrives, the API fetches the bytes and writes them straight to the response. It does no database query and no JSON encoding. The cache is invalidated when the user does a write (POST or PUT) or when an upstream event changes their data. The filler then rebuilds the entry.

Design choices.

  • Persistence is off. Redis persistence (RDB snapshots or the AOF log) can require extra memory, up to double during a snapshot fork in the worst case. Zerodha runs Redis as a pure in-memory cache and rebuilds from the source if needed.
  • High availability by independent copies. Instead of Redis Sentinel or Cluster replication, multiple independent Redis instances hold the data.
  • Only today's data. The working set is a few hundred GB, which fits in RAM across a few servers.

10.1: Dumb caching. The cache stores the exact bytes the client will receive. The API is then just a byte pump with authentication. There is no business logic on the read path.

10.2: Some in-process state is fine. Some reference data, such as the instrument master list with on the order of 100,000 rows, is loaded into each service's memory at boot. To refresh it, restart the service. Restarts are cheap and the data changes daily.

10.3: HTTP caching with ETags. The API sets an ETag on each response, a short tag representing that version of the resource. The client sends it back in If-None-Match. If the data is unchanged, the server replies 304 Not Modified with no body. Zerodha stores the current ETag per user per resource in a Redis map. Invalidating the cache deletes the tag, so the next request gets a full 200 response. The post says this saves terabytes of transfer a month. Mobile apps also cache responses locally and use the same mechanism. See HTTP and HTTPS and caching strategies.

Overlooked constraints.

  • The filler is now the bottleneck and the risk. If the filler lags at market open, users see stale positions. The design moves load from the read path to the write path, and that path must keep up with bursts.
  • Independent copies can disagree. Without replication, two Redis instances can briefly hold different versions. Clients must tolerate that, or one instance must be primary for reads.
  • ETag correctness depends on invalidation. A missed invalidation means a client keeps receiving 304 for stale data until something else changes. The tag must be deleted on every path that changes the data.

What Zerodha sacrificed. Strong consistency on reads. A user might see their order book a fraction of a second behind the OMS. It also gave up Redis durability: a restart means an empty cache and a rebuild. In exchange it got predictable sub-millisecond reads under any load.

Deep Dive: sizing the hot cache and the ETag savingShow

Cache size (handbook's illustration). 2 million active users each have about 8 cached resources (orders, positions, holdings, margins, profile and so on), averaging 20 KB of JSON each. That is 2 million × 8 × 20 KB = 320 GB, consistent with the post's "a few hundred GB". Spread over 4 Redis servers with 128 GB each, it leaves headroom. With persistence enabled, a fork for an RDB snapshot can need extra memory for copy-on-write pages during heavy writes. Disabling it removes that risk.

ETag saving (handbook's illustration). Suppose the apps poll orders and positions every 5 seconds for 6 hours a day across 500,000 active sessions. That is 500,000 × 2 × 4,320 = 4.3 billion requests a day. If 90 percent of polls find nothing changed and the average body is 15 KB, then 3.9 billion × 15 KB ≈ 58 TB a day would have been sent. A 304 response is a few hundred bytes. The saving is in the tens of terabytes a month, in line with the post's claim.

Pre-serialised bytes. Encoding a 20 KB JSON response in Go takes perhaps 50 to 200 microseconds and allocates memory the garbage collector must reclaim. At 100,000 requests per second, that is 5 to 20 CPU cores just for encoding. Storing bytes once at write time and serving them unchanged removes that cost. It also connects to points 11 and 12 in Lesson 7.

Lesson 7: Serialisation, allocation, concurrency, fast tech and vertical scaling (2020)#

Assumptions. Points 11 to 16 assume a garbage-collected language (Go or Python) on a busy server, where CPU time and GC pauses add directly to tail latency. They also assume that one well-used large machine is often better than many small ones.

Point 11: serialisation is expensive. Converting objects to JSON or another format allocates memory and burns CPU. In a garbage-collected language, every allocation is future GC work. Avoid repeated serialisation of the same data (Lesson 6's pre-serialised cache) and choose efficient formats for hot paths. The ticker sends binary packets, not JSON.

Point 12: allocation is expensive. Reuse buffers instead of allocating new ones per request. In Go, avoid values that escape to the heap when they could stay on the stack, and use pools (sync.Pool) for temporary buffers. In Python, use __slots__ on classes with many instances to avoid a per-object dictionary. Zerodha's logging library for Go is designed to be zero-allocation (Lesson 16).

Point 13: use concurrency well. The post's example is a job that imported a large JSON-lines file by reading a line, parsing it and writing it to the database, one at a time. It was rewritten as a pipeline: one goroutine reads lines, N worker goroutines (one per CPU core) parse and transform them, and one goroutine batches the writes. The result was orders-of-magnitude faster. The reader is I/O bound, the workers are CPU bound and the writer benefits from batching. Each stage runs at its own best speed.

Point 14: use fast technology. In 2014 Zerodha evaluated Python, C++, Java, Node.js and Erlang for its first performance-critical service and chose Go. Go is compiled, has cheap goroutines, a good standard library for networking and a single static binary to deploy. The ticker is a single Go binary that serves hundreds of thousands of WebSocket connections. The post also advises avoiding large frameworks on hot paths, because they hide allocations and add layers.

Point 15: scale vertically first. A modern server with dozens of cores and hundreds of GB of RAM is enormous. Many systems that "need" a cluster would fit on one or two such machines. The post mocks the opposite habit, joking about an "enterprisely" architected system that needs 128 CPUs and 512 GB of RAM to serve 2,000 requests per second. Vertical scaling avoids distributed-system problems entirely: no consensus, no network partitions and no cross-node joins.

Point 16: the human impediment. The biggest obstacle to scaling is often people: fashion-driven choices, fear of changing things, and organisational habits. Technology problems are usually the easier part.

Overlooked constraints.

  • Vertical scaling has a ceiling and a blast radius. One huge machine is one failure domain. Zerodha pairs big machines with replicas and failover, not with a single box.
  • Go is not automatically fast. Interfaces, reflection-based JSON and careless allocation make Go programs slow. The speed comes from the discipline in points 11 and 12.
  • Pipelines need backpressure. If the writer is slower than the workers, bounded channels must slow the reader down, or memory grows without limit.

What Zerodha sacrificed. Some developer convenience: hand-tuned code with pooled buffers and pre-serialised bytes is harder to write than idiomatic framework code. Vertical scaling sacrificed the theoretical ability to grow without limit, a limit Zerodha has not hit.

Deep Dive: what one big machine can doShow

Rough capacity (handbook's illustration). A 64-core server running a Go API that does a Redis GET and writes the bytes might handle 20,000 to 50,000 requests per second per core-group of 8, so a few hundred thousand per machine. Zerodha's peak of hundreds of thousands of requests per second then needs a handful of servers. They are there for redundancy as much as capacity.

The "enterprisely" ratio. 2,000 requests per second on 128 CPUs is about 16 requests per second per core. That is about 60 ms of CPU per request. A Go service doing one cache lookup uses tens of microseconds of CPU. The thousandfold gap comes from layers: frameworks, ORMs, serialisation, service-to-service hops and logging.

When to stop scaling up. Scale out when:

  • Failover needs it. Losing a machine would breach your availability target.
  • Writes outgrow one node. Write volume exceeds one primary's I/O or WAL throughput.
  • The data outgrows one node. It no longer fits on local storage with room to grow.
  • Cost stops scaling linearly. The next size up costs much more per core than two smaller machines.

Zerodha's Postgres hit the third point and responded with partition-based sharding (Lesson 10), not a distributed database.

Lesson 8: Zerodha against the classic "scale to millions" ladder#

The system design primer's exercise "Design a system that scales to millions of users on AWS" is the standard textbook path. Comparing it with Zerodha's choices shows which steps are universal and which depend on context. See also scaling from zero to millions.

The primer's assumptions. 10 million users, 1 billion writes and 100 billion reads a month (a 100 to 1 read to write ratio), 1 KB per write. That gives 1 TB of new data a month and 36 TB over three years. With about 2.5 million seconds in a month, that is 400 writes and 40,000 reads per second on average. Its method is iterative: benchmark or load test, profile to find the bottleneck, fix it while weighing alternatives, and repeat.

The primer's ladder and Zerodha's version.

Primer stepWhat the primer doesWhat Zerodha doesWhy
Single boxOne EC2 instance with MySQL, scale vertically, basic monitoring, a static IP, DNS, only ports 80, 443 and whitelisted 22 openAgrees: scale vertically first, measure everythingSame logic: avoid distribution until needed
Users+Static files to S3, database to managed RDS, VPC with public and private subnets, encryptionSelf-managed Postgres on EC2 and bare metal; S3 for files; private networks and a zero-trust VPNManaged RDS costs more and limits tuning (autovacuum off, custom partitions)
Users++ELB or HAProxy, multi-AZ web servers, SSL termination at the load balancer, separate web and app tiers, MySQL primary-replica failover, CDNHAProxy and Nginx with keep-alive pools (Lesson 5), Postgres primary plus replica, failover via snapshotsAgrees on the shape; prefers self-run proxies
Users+++Memory cache (ElastiCache) for hot data and sessions, so web servers become stateless; try the database's own cache first; read replicasHot Redis with pre-serialised bytes for all Kite reads (Lesson 6); report cache for Console (Lesson 11)Agrees strongly; goes further by never reading the DB on the hot path
Users++++Autoscaling on time-of-day or metrics; configuration management (Chef, Puppet, Ansible); host and aggregate monitoring, logs, external checks, PagerDuty, SentryFixed capacity for the market day; ephemeral clusters for nightly batch (Lesson 15); Salt; Prometheus, VictoriaMetrics, ClickHouse logs, SentryMarket load is predictable to the minute, so pre-provisioning beats reactive autoscaling
Users+++++Data warehouse (Redshift); federation, sharding, denormalisation, SQL tuning; NoSQL; queues and workers for async jobsDenormalised Postgres, sharding by financial year with postgres_fdw (Lesson 10), ClickHouse for analytics; Kafka and Redis-backed job queuesSame patterns, applied with fewer, self-hosted components

The primer's memory numbers explain why caching is the biggest step: reading 1 MB sequentially from memory takes about 250 microseconds, from SSD about 4 times longer and from spinning disk about 80 times longer.

Overlooked constraints.

  • The primer assumes traffic follows business hours loosely. Zerodha's traffic follows exchange hours exactly, which makes autoscaling less useful and pre-provisioning more useful.
  • The primer assumes managed services are cheap relative to staff. For a company with deep operations skill and large volume, self-hosting reverses that.
  • Both ignore regulation. Log retention, audit trails and data residency shape Zerodha's choices as much as load does.

What Zerodha sacrificed by leaving the ladder. The safety of managed services (automatic backups, patching, failover in RDS), and elasticity for unpredictable growth. It accepted owning more operational work in exchange for control and cost.

Deep Dive: the primer's numbers applied to a brokerShow

Converting rates. The primer's handy conversions: 1 request per second is about 2.5 million a month; 40 per second is 100 million a month; 400 per second is 1 billion a month.

Averages hide peaks (handbook's illustration). Zerodha's 12 million trades a day mostly happen in 6.25 market hours. That is 12 million ÷ 22,500 seconds ≈ 530 trades per second on average during the session. But perhaps 15 percent of them come in the first 15 minutes: 1.8 million ÷ 900 ≈ 2,000 per second, four times the session average. Each trade may involve 5 to 10 orders, modifications and status reads, plus many more position and quote reads. So the opening minutes need capacity for roughly 10 times the daily average request rate. That matches the post's "10 times bursts in 10 seconds".

Storage. 12 million trades a day at about 500 bytes per row with indexes is 6 GB a day, about 1.5 TB a year for trades alone. Add ledgers, orders, contract notes and reports, and multi-year retention lands in the tens of TB, the same range as the primer's 36 TB. The difference is that regulations require Zerodha to keep and query years of it. That pushes it toward partitioning by time and sharding by financial year.

Family 3: Data

Lesson 9: Working with PostgreSQL at hundreds of billions of rows (2021)#

Assumptions. This post covers the databases behind Console, Zerodha's back office for reports, profit and loss (P&L), ledgers and tax statements. The assumptions:

  • Traffic. Up to 40,000 to 50,000 queries per second at peak on the largest warehouse database, even with a hot cache in front of it (Lesson 11).
  • Write pattern. Tens of millions of new rows a day, and 99 percent of writes happen at night. EOD processes reconcile large files from the exchanges after the market closes. During trading hours writes are rare. On nights and holidays user activity is almost nil, which leaves maintenance windows.
  • Data. Hundreds of billions of rows, close to 20 TB, across four sharded nodes. Most rows are immutable: trades, P&L entries and ledger lines. Millions are still deleted and garbage-collected regularly as part of financial reconciliation.
  • Consistency. Reports must be exact, but they can be up to a day old. Today's trades appear after tonight's EOD.
  • Maintenance. The team self-hosts on plain EC2 instances, not a managed service. High availability is a simple failover replica. Backups are AWS disk snapshots.

History. For several years everything ran on one primary and one replica, each a 32-core, 64 GB EC2 instance. That setup stored and served billions of rows without trouble. The team moved to multiple shards around 2020 as data grew fast, more to be future-proof than because the single primary had failed.

Schema choices.

  • Denormalise to avoid big joins. Joins across tables with billions of rows are hard to keep fast. The team copies parent columns into child tables so most queries touch one table, or one table plus a materialised view. Joins across more than two large entities are rare.
  • Materialised views hold the results of frequent, expensive queries as snapshots refreshed asynchronously. They also reduce the need for extra indexes, because the expensive scan happens once.
  • Drop foreign keys. Foreign key checks slowed the nightly bulk imports of tens of millions of rows significantly. Integrity is guaranteed by the import process instead of by the database.
  • No auto-increment IDs. For this data, a surrogate ID column is unnecessary. Removing it saved a lot of disk across billions of rows and sped up bulk inserts.
  • Partition by month. Nearly every row has a meaningful date: a trade date, a P&L day or a price date. Tables are partitioned by month on that timestamp. Daily partitions were tried. They made inserts faster, since each night's import filled a fresh, empty partition, but range queries became much slower because they had to touch many partitions. Most user reports fall within a month, so monthly partitions were the better trade-off.
  • Temp table for today's data. Inserting into a monthly partition gets slower as the month fills. So each night's data is bulk-inserted into a temporary table. That table serves the next day's queries, which are a large share of traffic, and is synced into the main partition asynchronously.

Tuning parameters. The post treats tuning as continuous, because data and user behaviour change.

  • work_mem. This is memory per sort or hash operation, per backend. The post warns that total use can approach work_mem times max_connections, and max_connections can stay high at peak even with pooling. Set it wrong and the server runs out of memory. Zerodha uses about 600 MB, compared with the 4 MB default, because its report queries sort and join large row sets. The right value also depends on disk speed. On a slow, badly designed database, large work_mem just means more memory tied up by hanging connections.
  • shared_buffers. This is Postgres's own page cache. Run EXPLAIN ANALYZE on the heavy queries and check whether they hit the buffer cache. Increase the setting until they do, but not much beyond a third of RAM, or other memory needs suffer. If you want the whole database in memory, the post says, use Redis instead.
  • effective_cache_size. This tells the planner how much OS file cache it can expect. Example from the post: on a 64 GB server, if shared_buffers is 30 GB and work_mem times connections is about 10 GB, roughly 24 GB remains for the OS cache. Telling the planner this makes it more willing to use index scans that will hit cached pages.
  • max_parallel_workers. Zerodha prefers database servers with many cores. It sets max_parallel_workers to the number of cores and max_parallel_workers_per_gather to half of that, leaving room for other workers such as replication. A query that spans several monthly partitions can then scan them in parallel and gather the results.

Vacuuming. Postgres implements MVCC by keeping old row versions. VACUUM reclaims them, and ANALYZE refreshes planner statistics. The post's advice for a batch-heavy database: turn autovacuum off, so it does not start in the middle of a bulk import and fight for locks and I/O. Run VACUUM ANALYZE on the most-changed partitions from cron as part of the EOD process. On large tables this can take hours if done rarely, so do it every day. For databases with steady daytime writes, keep autovacuum on but set its thresholds so it runs after a meaningful number of changes, not constantly. See storage engines and concurrency control.

Indexing and diagnostics.

  • Avoid over-indexing. Each index slows the nightly import.
  • Index precisely. Index columns the way queries search them, using partial indexes (only rows matching a condition) and composite indexes. Do not add an index for a query that runs once in a while. A sequential scan is sometimes the right plan.
  • Run EXPLAIN ANALYZE on every change.
  • Check table health. pg_stat_user_tables shows when each table was last vacuumed and analysed.
  • Find expensive queries. The pg_stat_statements extension shows total time and call counts per query, which points to the queries and tables that need attention.
  • Use CTEs. Common table expressions make complex queries readable. Used well, they also help the planner.

Hot takes from the post. Poor indexing and poor vacuuming cause almost all RDBMS performance problems. You rarely need a distributed database; you need better indexes. Do not go multi-shard until data heads past a few TB, but plan so you can. Storing less is often better than storing everything. For old reports, Zerodha stores data at date checkpoints and incremental diffs, then recomputes forward from the nearest checkpoint when a rare old report is requested. That spends CPU later to save disk and pain now. The fastest queries run on tables with less data. The post also contrasts Postgres with MySQL. The team had data consistency issues, corruption, odd NULL and empty-value behaviour and memory leaks with MySQL. Postgres has been solid since 2013, with upgrades from 9 to 10, 11 and 12 bringing free performance gains.

Overlooked constraints.

  • Turning off autovacuum is only safe with discipline. If the cron job fails silently, dead rows pile up and transaction ID wraparound becomes a risk. Postgres will eventually force an aggressive anti-wraparound vacuum or stop accepting writes. Monitoring last-vacuum times is mandatory.
  • Dropping foreign keys moves integrity into code. Every import and reconciliation must guarantee consistency itself, and bugs show up as orphan rows, not errors.
  • High work_mem is a loaded gun. One bad query with many hash joins can use several times work_mem. This setting is safe only with a controlled number of concurrent heavy queries, which the report queue in Lesson 11 provides.

What Zerodha sacrificed. Normalisation and database-enforced integrity, in exchange for import speed and simpler queries. Live freshness, since reports reflect the last EOD. And the protection of autovacuum's defaults, in exchange for predictable nightly maintenance.

Deep Dive: partition granularity, worked with numbersShow

Setup (handbook's illustration). A trades table receives 20 million rows a night and holds 5 years of data. The average report asks for one user's trades over 30 days.

Daily partitions. 5 years is about 1,250 trading days, so 1,250 partitions. Each night's import goes into an empty partition with no index bloat, which is fast. A 30-day report touches about 21 trading-day partitions. The planner must open 21 indexes and merge the results, and planning time itself grows with partition count. At thousands of partitions, planning can add milliseconds per query.

Monthly partitions. 60 partitions. A 30-day report touches 1 or 2. But by the 25th of the month, a partition holds about 400 million rows. Inserting 20 million more means updating indexes with about 400 million entries, which is slower than inserting into an empty table. That is why Zerodha imports into a temp table and syncs later.

Why the temp table works. The next day, most queries are about yesterday's trades. Those hit a small, freshly loaded table that is probably fully in cache. Older queries hit the monthly partition. The asynchronous sync runs when load is low.

Checkpoint and recompute. Storing a full holdings snapshot per user per day for 5 years at 6 million users would be about 7.5 billion snapshot rows. Instead, store a snapshot at each month end (60 per user, 360 million rows) and the daily trade diffs, which are stored anyway. A rare request for a mid-month date loads the month-end snapshot and replays at most 20 days of trades, a few hundred rows. Storage falls about 20 times. The cost is a few milliseconds of computation on a rare query.

Lesson 10: Sharding by financial year with foreign data wrappers (2021)#

Assumptions. The single primary still worked, but signs of strain were growing:

  • Maintenance windows were shrinking. Nightly bulk imports and the vacuum after them were getting slower and might not fit in the overnight window.
  • Recovery time grew with size. After a crash or a restart for a parameter change, a huge database takes longer to come back. The team wanted to avoid a database too big to recover in time.
  • Cold data cost as much as hot data. Old financial years were queried less and less but sat on the same expensive disks and cores as the current year. Without separating them, resources grow forever.

The constraints for any solution: change data and queries as little as possible, move older financial years to smaller servers, and stay on Postgres. (ClickHouse was being explored separately for some immutable data, mainly for disk savings.)

Option 1: Citus. Citus is a Postgres extension that distributes tables across nodes, with routing, failover and parallel queries. The team rejected it because it would mean adding a distribution column to every sharded table. Hundreds of existing queries would need rewriting, and altering multi-TB tables would take an unknown amount of time and space.

Option 2: postgres_fdw. A foreign data wrapper (FDW) lets Postgres query an external data source as if it were a local table. postgres_fdw is the one for other Postgres servers. Since Postgres partitions can be foreign tables, a partitioned table on the primary can have some partitions local and others on remote servers. Queries do not change.

The migration (under two hours, in an off-market window).

  1. Snapshot. Take EC2 disk snapshots of the primary and restore them onto new instances, each with its own failover replica. Each new node starts with a full copy.
  2. Connect. Set up FDW connections from the primary to the new nodes.
  3. Trim the primary. A script drops the older monthly partitions on the primary and replaces each with a foreign table pointing at the shard that holds that financial year.
  4. Trim the shards. Another script drops current-year partitions from the shards, so each keeps only its own years.
  5. Repeat yearly. After each financial year closes, move it off the primary the same way.

Dropping a partition in Postgres is fast because it removes whole files instead of deleting rows. That is why the process fits in two hours with no schema change. Older years move to progressively cheaper, less powerful servers.

Limitations. Data from remote partitions travels over the network, so aggregations over long ranges are slower. Postgres cannot parallelise one query across nodes. The team accepted both because old-year queries are rare and the hot cache absorbs repeat reads.

Overlooked constraints.

  • Foreign table pushdown is partial. postgres_fdw pushes down filters, and in newer versions many joins and aggregates. Some queries still pull many rows across the network before filtering. Check plans for remote queries.
  • Writes to old years go through the FDW. Corrections to past financial years still work, but they are distributed writes without a global transaction guarantee across nodes. Here such writes are rare and done in batches.
  • Each shard is its own failure domain. Losing an old-year shard breaks queries that touch that year. Each shard needs its own replica and backups.

What Zerodha sacrificed. Cross-node parallelism and single-node simplicity, in exchange for an almost free migration. Compared with a distributed SQL database, Zerodha gave up automatic rebalancing and online resharding. It gets predictable, manual, yearly moves instead, which suits time-partitioned data perfectly. See partitioning and sharding.

Deep Dive: why time-based sharding fits financial dataShow

Access skew (handbook's illustration). Suppose 90 percent of report queries concern the current financial year, 8 percent the previous year and 2 percent older years. With 20 TB over 6 years, the primary holds about 4 TB but serves 90 percent of queries. The shard for last year holds 4 TB and serves 8 percent. Older shards share 12 TB and 2 percent of the queries. If the primary is a 64-core machine, a 16-core server is enough for last year and an 8-core server for older years. Compute cost for old data falls by a factor of 4 to 8.

Hash sharding comparison. Hash-sharding by user ID would spread hot current-year data across every node. Every node would then need to be powerful, and every query for one user would still hit one node. Rebalancing would mean moving data between nodes. Time sharding instead matches how financial data ages: once a year closes, it rarely changes and is rarely read. The cost is that a query spanning years touches several nodes.

Recovery time. Postgres crash recovery replays WAL since the last checkpoint, so its time depends more on write volume than total size. But restore from backup, base backups for new replicas and full-table vacuum all scale with size. A 4 TB primary restores from a snapshot about 5 times faster than a 20 TB one. That is one of the post's motivations.

Lesson 11: sql-jobber (dungbeetle): Postgres as a hot cache for reports (2021)#

Assumptions. Tens of thousands of users at once pull trade history, P&L and tax reports from Console. Each report query may scan millions of rows. Users then sort, filter and page through the result many times. The post assumes:

  • Traffic. Even fast queries against a database with billions of rows cannot serve tens of thousands of reports per second. Re-running the query for each sort and filter would snowball.
  • Shape. There are dozens of report types, each with many columns and filters.
  • Lifetime. A report result is only useful for that session or that day.

Why not Redis. Caching results in Redis would mean implementing sorting and filtering for dozens of report types in application code, and would need ever more RAM.

The idea. Use a separate Postgres instance as the cache. When a user requests a report, a job runs the heavy query against the large database. It writes the result into a new table created just for that job in the cache database, with columns derived from the result. All later sorting, filtering and paging run as simple SQL on that small table. The post compares it to a materialised view per query, stored in a different database.

sql-jobber. Zerodha built and open-sourced a distributed job queue for this, named sql-jobber and later renamed dungbeetle. It queues heavy SQL read jobs. It runs them against the backend databases only as fast as their capacity allows, which throttles load on the big database. It stores each result as its own table in one of possibly many cache databases. The queue is how Zerodha keeps peak load on the primary bounded no matter how many users click "generate report".

Scale and lifecycle. The cache database accumulates tens of millions of tables a day. Each night the whole cache database is dropped and recreated empty. It serves millions of reports a day.

Cache database tuning.

  • max_connections is high. The cache acts as the primary server for user reads.
  • work_mem is a few MB. There are no joins, and each table holds a few hundred or thousand rows.
  • fsync and the write-ahead log are off. If the cache restarts, its data can simply be thrown away.
  • Replication is off. An ephemeral cache does not need a replica.
  • shared_buffers is sized to the average total size of the tables created during a peak hour.

Overlooked constraints.

  • Catalog bloat. Tens of millions of tables means a very large system catalog. Lookups of table metadata slow down. Nightly recreation keeps this bounded.
  • Crash means losing every cached report. With fsync off, an OS crash can corrupt the cache database. The design accepts that and recreates it, so users simply regenerate reports.
  • Queue fairness. A queue with a capacity limit needs per-user or per-type fairness, or one user requesting many large reports delays everyone.

What Zerodha sacrificed. Freshness and durability of results: a report is a snapshot of the moment it ran, and cache contents vanish nightly or on a crash. It also accepted queueing latency, because users wait seconds for a report during peaks instead of overloading the warehouse.

Deep Dive: why a SQL table beats a key-value cache for reportsShow

Filter and sort cost (handbook's illustration). A P&L report has 2,000 rows and 15 columns. A user applies 10 different sorts and filters. With a key-value cache, the app fetches the 2,000-row blob 10 times (about 300 KB each), deserialises it and sorts in memory. That works, but sort logic for each report type must live in code. With a cache table, each operation is one SQL statement on a 2,000-row table, a sub-millisecond scan in shared buffers. The database already implements every sort, filter and pagination.

Throttle math. If the warehouse can sustain 200 concurrent heavy queries and each takes 500 ms, it completes 400 reports per second. If 20,000 users click at once in the morning, the queue drains them in 50 seconds, and the database stays healthy. Without the queue, 20,000 concurrent heavy queries would each take far longer. With high work_mem (Lesson 9), memory would run out first.

Durability off. Turning off fsync and WAL can make writes several times faster, because each commit no longer waits for disk flushes. For an ephemeral cache, losing data is acceptable, so this is pure gain. It is the same reasoning as Redis with persistence disabled in Lesson 6.

Lesson 12: Blobasaur, distributed blob storage on SQLite (2026)#

Assumptions. Kite has about 20 million customers. They save multi-chart layouts, indicator templates, drawings and UI preferences, and in Terminal mode they build drag-and-drop workspaces. Services store these as opaque blobs, mostly JSON, from a few KB to several MB. The workload:

  • Traffic. Thousands to tens of thousands of requests per second, bursty with market volatility. About 50 percent of traffic is writes, because users constantly tweak and resave layouts.
  • Latency. Single-digit milliseconds whether the blob is a 2 KB settings object or a 5 MB chart layout.
  • Consistency and durability. Relaxed. This is UI state, not financial data. Losing a recent layout tweak in a power cut is annoying but never affects trading.
  • Maintenance. A small team that must run and understand the store. Simple key-value and hash CRUD with TTLs, no complex queries.

History. Blobs were first stored in CouchDB, which could not keep up. Then came SSDB, a C++ disk-backed store that speaks the Redis protocol. It worked for years, but it became unmaintained, and C++ is outside the team's expertise. It also runs on one node only. Latency degraded on large payloads enough that blobs had to be capped at 1 MB.

Alternatives evaluated and why each was rejected.

OptionWhy not
ScyllaDBAlready in use, but lower throughput and higher resource use for multi-MB blobs; tombstones from frequent overwrites and TTL expiry need careful tuning
Postgres BYTEAPoor performance and disk efficiency for this pattern
YugabyteDBBlob storage is not its focus; too large a system
RocksDBRight primitives, but not built for high-throughput multi-MB writes
CephToo complex to operate; not even tried
SeaweedFSClosest fit, but appends on overwrite until compaction (disk grows on overwrite-heavy use), needs a separate map from user key to blob ID, no per-blob TTL, many parts
S3 or MinIOHigh per-request latency for small blobs, high request cost when half of traffic is writes, coarse lifecycle TTLs
Raw filesMust build atomic writes, batching, TTL indexes, metadata and fd and inode management

Why SQLite. SQLite's own benchmark claims it can be about 35 percent faster than the filesystem for reading and writing small blobs, because it avoids per-file open and close overhead. Raw files win above about 100 KiB. After compression, 99 percent of Zerodha's values are well below that. SQLite also brings ACID transactions, crash recovery and inspection with the standard sqlite3 CLI.

Why Rust. Go's standard SQLite driver needs CGo. That complicates static builds, pins OS threads during C calls under high concurrency, and adds GC pressure when compressing multi-MB buffers. Rust (tokio, sqlx, rusqlite) calls SQLite's C API directly with predictable memory and ships as one static binary.

Redis protocol compatibility. Existing Go and Python services used standard Redis clients with GET, SET, HGET, HSET, DEL and EXPIRE. Speaking the same protocol made Blobasaur a drop-in replacement.

Architecture on one node.

  • Shards are SQLite files. In WAL mode a SQLite database allows many concurrent readers but only one writer at a time. With 50 percent writes, one file per node would bottleneck. So each node splits data across many SQLite files. Each key maps to one shard by multi-probe consistent hashing.
  • One writer per shard, with group commit. Each shard has a dedicated writer task fed by a bounded queue. It drains a batch of pending writes (batch_size 50 in the benchmark) and commits them in a single BEGIN IMMEDIATE ... COMMIT transaction, spreading the transaction and WAL cost over many clients.
  • Concurrent readers. Reads use a per-shard pool of read-only connections that run alongside the writer.

Benchmark: 1 shard against 16. 64 concurrent connections, 64 KiB JSON payloads (about the production average, compressing about 9 times with zstd), 100,000 keys, synchronous writes, data on tmpfs. Both setups had 1,600 MB of page cache and 64 read connections, on a 16-core laptop shared with the load generator.

Workload1 shard16 shards
HSET only7,740 ops/s, p99 10.7 ms25,324 ops/s, p99 8.3 ms
50 percent HSET, 50 percent HGET14,227 ops/s, p99 10.5 ms29,538 ops/s, p99 8.5 ms
HGET only67,128 ops/s, p99 2.1 ms70,884 ops/s, p99 2.3 ms

Sharding raised write throughput 3.3 times and cut median write latency from 8.2 ms to 2.1 ms. Reads barely changed, because WAL readers already run concurrently. At 25,324 writes per second of 64 KiB, the node pushes about 1.66 GB per second of JSON through zstd.

Schema. Each shard has a blobs table with key (primary key), data, created_at, updated_at, expires_at and version, plus a partial index on expires_at for rows that have a TTL. Rows without a TTL take no space in that index. Hash commands (HSET prefs user42 ...) write to a per-namespace table named blobs_ plus the namespace, for example blobs_prefs. Reads filter out expired rows, and a background worker deletes them later.

Compression. Blobasaur supports zstd, lz4, gzip and brotli; production uses zstd. Over an hour of production HSET traffic, the average payload shrank from 63.6 KiB to 5.5 KiB (about 11 times) and the p99 from 935 KiB to 59.3 KiB (about 16 times). With 4 KiB SQLite pages, an average blob goes from about 16 pages to about 2. That means less page cache pressure and less WAL traffic.

Durability. WAL mode with synchronous = NORMAL. SQLite does not fsync on every commit, so an OS crash or power loss can lose the last committed transactions but never corrupts the database. An optional async_write mode acknowledges a write as soon as it is in the shard's memory queue, before the batch commits.

Across machines. Blobasaur implements the Redis Cluster protocol. The keyspace has 16,384 hash slots chosen by CRC16 of the key. Each node owns a configured range of slots, nodes discover each other by gossip, and a node replies MOVED to redirect a client that sent a key to the wrong node. So routing has two levels: CRC16 picks the machine, then consistent hashing picks the SQLite shard on it. Slot assignment is static for now; live rebalancing and automatic failover are not implemented.

Resharding. With naive hash-mod-N, growing from 4 to 5 shards moves about 80 percent of keys. With consistent hashing only about 20 percent move, the share that belongs to the new shard. Resharding is an offline CLI operation: stop the server, run "blobasaur shard migrate 4 5 --verify", update the config and restart. See consistent hashing.

Migration from SSDB.

  1. New workloads first. Kite's Terminal mode stored workspaces in Blobasaur from day one.
  2. Dual-write and backfill. Existing services wrote to both SSDB and Blobasaur while a background job copied historical keys. Reads went to Blobasaur and fell back to SSDB on a miss or error.
  3. Cutover. The only client change was switching from a single-node Redis client to a cluster-aware client with the three Blobasaur node addresses.

After a month of dual writes with zero discrepancies, SSDB was turned off. See data migration.

Lessons learned.

  • Deleting rows does not shrink SQLite files. Freed pages go to an internal freelist. The fix is auto_vacuum = INCREMENTAL plus a vacuum subcommand that frees up to a set amount (128 MB by default), followed by wal_checkpoint(TRUNCATE) to actually shrink the file in WAL mode.
  • Async writes must be visible to every read. Queued writes are kept in an in-memory pending map that reads check first. A bug appeared when a DEL followed immediately by a GET returned the old value, because the queued delete was not in the map. The fix was explicit tombstones in the pending map, with every read path (GET, HGET, EXISTS, TTL) checking it.
  • Expiry cleanup must share the writer. p99 write latency was normally under 5 ms but spiked to 30 to 50 ms. The TTL cleanup task opened its own write connection and ran one huge DELETE, fighting the shard writer for SQLite's single write lock. Routing cleanup through the shard's writer in chunks of 1,000 rows removed the spikes. Since reads already hide expired rows, slow physical deletion is harmless.

In production. Three nodes of 4 vCPU and 8 GB RAM. Over a full trading session, p99 across all commands is about 2 ms on every node and p50 is 250 to 550 microseconds. HSET p99 is about 2 ms, HGET about 1.4 ms and HDEL mostly under 1 ms. Blobasaur is open source under AGPLv3.

Overlooked constraints.

  • No failover yet. A node loss makes its slots unavailable until it is restored. That is acceptable for UI preferences, but not for anything critical.
  • Single writer per shard sets a ceiling. Write throughput per node is roughly the number of shards times one writer's batch rate. Hot keys all land on one shard and one writer.
  • Compression costs CPU. Pushing 1.66 GB per second through zstd uses many cores. Small nodes trade CPU for disk and I/O, which works because 4 vCPUs handle production load with headroom.

What Zerodha sacrificed. Strict durability (synchronous = NORMAL and optional async writes), automatic failover and live rebalancing. It also took on a new piece of software to own, written in a language outside its main stack. In return it got a store that fits the exact workload: small nodes, drop-in protocol compatibility, compression and per-key TTL. This connects to handling large blobs. Where that pattern sends large files to object storage, Zerodha shows why many small-to-medium, overwrite-heavy blobs with tight latency do not fit object storage.

Deep Dive: group commit, the single-writer limit and consistent hashingShow

Why group commit helps. A SQLite commit in WAL mode appends frames to the WAL and, with synchronous = FULL, fsyncs. Even with NORMAL, each transaction has a fixed overhead for locking, WAL header updates and page writes. Suppose that overhead is 1 ms and the per-row cost is 0.05 ms (handbook's illustration). One write per transaction caps a shard near 950 writes per second. A batch of 50 costs 1 + 50 × 0.05 = 3.5 ms, which is about 14,000 writes per second per shard. Batching trades a little added latency for each write (waiting for the batch) for much higher throughput, the same idea as group commit in Postgres and Kafka's producer batching.

Why more shards help writes but not reads. With one SQLite file, every write waits for the single writer lock. With 16 files, up to 16 writers run in parallel, limited by CPU and disk. In WAL mode readers never block the writer and vice versa, so read throughput was already near the CPU limit with one shard.

Multi-probe consistent hashing. Classic consistent hashing places each shard at many points (virtual nodes) on a ring to balance load. Multi-probe consistent hashing (Appleton and O'Reilly, Google, 2015) places each shard once but hashes each key several times. It picks the probe that lands closest to a shard. This gives good balance without the memory of virtual nodes. Adding a fifth shard to four moves only the keys that now map to the new shard, about 1/5 of the total.

Two-level routing. CRC16 mod 16,384 slots across machines lets clients route directly with standard Redis Cluster libraries. Consistent hashing within a machine lets the number of local SQLite files change without touching the cluster slot map. Each level solves a different resharding problem.

Family 4: Batch at a regulatory deadline

Lesson 13: 1.5 million contract notes in 25 minutes: the pipeline (2024)#

Assumptions. After each trading day, a broker must email every client who traded a digitally signed PDF called a contract note. It itemises each trade and its charges. Its layout, contents and delivery deadline are set by regulation: it must arrive before the next session. The assumptions:

  • Volume. More than 1.5 million clients trade on an average day, and twice that on a volatile day.
  • Timing. The job can only start after the back office finishes reconciling exchange files, which themselves arrive late sometimes. So the usable window is a few hours of the night, and delays upstream eat into it.
  • Size variance. Most notes are 100 to 200 KB, a couple of pages. A prolific trader's note can run to thousands of pages.
  • Consistency. Every client must receive exactly their own correct note. Duplicates are embarrassing; missing notes are a compliance breach.
  • Maintenance. It runs once a night. Whatever runs it should cost nothing when idle.

The old stack and why it broke.

  1. Render to HTML. A Python program read exchange CSV dumps and rendered HTML with Jinja templates.
  2. Convert to PDF. Headless Chrome, driven by Puppeteer, turned the HTML into PDF.
  3. Sign. A Java command-line tool signed each PDF.
  4. Email. Self-hosted Postal SMTP servers sent the emails.

All of this ran on one large, vertically scaled server spun up for the job. It took 7 to 8 hours, and longer on heavy days. Postal itself became a bottleneck. With an 8-hour job starting late at night, a delay upstream could push delivery past the next market open.

The design principle. The team concluded it needed horizontal scale, but rejected functions-as-a-service (FaaS). Cold starts, per-invocation overhead, communication cost between functions and per-run pricing all hurt a CPU-bound batch of millions of units. Instead, the job runs on large ephemeral instances whose CPU cores are kept saturated, and destroys them as soon as the last job finishes. The work is broken into independent stages:

  1. Process data: turn exchange data into per-client template input.
  2. Generate PDF.
  3. Sign PDF.
  4. Email PDF.

Each stage has its own worker pool. Fine-grained resource planning is impossible because one client's note may be 2 pages and another's 2,000. So the design throws every job into a big pool of cores and lets the law of large numbers even it out. A 2,000-page note may hold one core 100 times longer than average, but with hundreds of cores busy, that barely affects the finish time.

Workers and the queue. The Python worker was rewritten as concurrent Go programs, which immediately cut time and resources by orders of magnitude. Distribution uses Tasqueue, a small pluggable Go job library the team wrote after evaluating existing options. Job functions are registered by name (generate_pdf, sign_pdf, email), and a chain links them so that one job's completion enqueues the next for the same client. Each worker downloads its input from S3, does its work and uploads its output to S3 for the next stage.

Redis as broker and state store. One Redis instance plays two roles. It is the queue broker that distributes jobs, and it records the status of every job. Operators can count processed, failed and pending jobs at any time. Failed or unprocessed clients get targeted retries: only their chains are rerun, not the whole batch.

PDF rendering: Puppeteer to LaTeX to Typst.

  • LaTeX with pdflatex. Moving templates from HTML to TeX was about 10 times faster than Puppeteer, with far fewer resources. It ran in production for a couple of months.
  • Memory limits. pdflatex cannot allocate memory dynamically, and thousand-page notes hit its limits whatever the tuning.
  • lualatex. This allocates memory dynamically and handled large reports better. But on huge tables it sometimes failed with stack traces that were nearly impossible to debug.
  • Image size. Docker images carrying TeX distributions and packages were large, which slowed worker start-up on fresh instances.
  • Typst. A modern typesetting system written in Rust and shipped as one static binary. It was 2 to 3 times faster than LaTeX on small documents. A 2,000-page note compiled in about 1 minute, against 18 minutes with lualatex. It also gave clearer error messages, needed no third-party packages for styling, and produced a much smaller image.

Signing. Regulation requires contract notes to be digitally signed and encrypted. The team found no fast FOSS library for batch signing, because PDF signatures are complex. So they wrapped the Java OpenPDF library in a small HTTP server. One JVM boots once and signs requests concurrently, avoiding a JVM start per file. It runs as a sidecar next to each signer worker.

Overlooked constraints.

  • Exactly once delivery is not free. A worker that sends an email and crashes before marking the job done will send it again on retry. Recording "sent" status in Redis immediately after the SMTP accept, and checking it before sending, narrows the window but cannot close it. See delivery semantics.
  • The slowest client sets the finish time. One very large note started late in the run can extend the whole job. Starting the biggest notes first (longest processing time first scheduling) shortens the tail.
  • Upstream lateness is not under your control. The design shortens the job so that a late exchange file still leaves enough slack. It does not remove the dependency.

What Zerodha sacrificed. A single, simple program on one box, in exchange for a distributed pipeline with a broker, object storage and an orchestrator. It also took on maintaining its own job library (Tasqueue), its own signing wrapper and a newer typesetting tool with a smaller ecosystem than LaTeX.

Deep Dive: why saturating ephemeral cores beats FaaS for this jobShow

Core-hours (handbook's illustration). Suppose each note needs on average 0.5 core-seconds to generate, 0.2 to sign and 0.05 to email, for 0.75 core-seconds total. 1.5 million notes then need about 1.1 million core-seconds, roughly 310 core-hours. Forty c6a instances of mixed sizes give on the order of 800 to 1,000 vCPUs. 310 core-hours over 900 cores is about 21 minutes of pure compute, consistent with a 25-minute run once start-up and the tail are included.

Cost. 40 instances for about 40 minutes including boot is roughly 27 instance-hours. Even at an average of 0.70 dollars an hour, that is under 20 dollars a night. The post calls the cost negligible, and this estimate agrees.

FaaS comparison. 4.5 million function invocations a night (3 stages times 1.5 million) at 1 GB of memory for 1 second each is 4.5 million GB-seconds. At typical serverless prices of about 0.0000167 dollars per GB-second, that is about 75 dollars, plus invocation fees. Cold starts for a JVM signer or a Typst container would add seconds to many invocations. Ephemeral VMs are cheaper and faster when the work is CPU-bound, predictable and large. FaaS shines when work is spiky, small and idle most of the time. See serverless.

Variance and pools. If note sizes follow a heavy-tailed distribution, the total work is dominated by a few large notes. With 900 cores, the largest note (1 minute with Typst) is under 5 percent of the run. With lualatex (18 minutes) it would have been most of the run. The typesetter change mattered for the tail as much as for the average.

Lesson 14: Seven million small files: EFS, EBS, S3 and the prefix trap (2024)#

Assumptions. Each stage passes files to the next through shared storage, so workers on different machines can pick up any job without copying files between them. A night produces about 7 million ephemeral files: Typst markup, PDFs and signed PDFs, mostly 100 to 200 KB and sometimes several MB. Storage must handle very high request rates for small files, in bursts, from dozens of machines. Files are worthless after the run.

The storage benchmark. The team concurrently wrote and read 10,000 files of 100 to 200 KB each:

  • EFS, General Purpose mode. EFS throttled throughput based on data size until the team provisioned 512 Mb/s. It then hit EFS's limit of 35,000 file operations per second, where a read counts as 1 operation and a write as 5. Writing the files took 4 to 5 seconds.
  • EFS, Max I/O mode. Higher latency per operation made it worse, 17 to 18 seconds. Dropped.
  • EBS. About 400 ms. Fast, but an EBS volume attaches to one instance, so it cannot be the shared hand-off between machines.
  • S3. About 4 to 5 seconds, similar to EFS General Purpose. Much cheaper than EFS with 1 TB stored and 512 Mb/s provisioned.
  • FSx for Lustre. Suggested by the AWS storage team for high-performance workloads. It was complex to set up and not available in ap-south-1 (Mumbai), the only region Zerodha operates in for this.

S3 won on cost and simplicity. The storage layer was rewritten on simples3, a small zero-dependency S3 client the team had written earlier.

The rate limit surprise. S3 supports at least 3,500 PUT, COPY, POST or DELETE requests and 5,500 GET or HEAD requests per second per prefix. Above that it returns 503 Slow Down. S3 adds capacity by splitting busy prefixes into more partitions over time. In a trial run of about 1.61 million requests in 5 minutes (about 5,300 per second), 0.13 percent failed even with 10 retries.

The cause. Each contract note's key started with a freshly generated KSUID. KSUIDs are designed to be sortable: they start with a timestamp. IDs generated within the same few minutes therefore share their first characters. Every key in the run began with the same five characters ("2CTgQ" in the post), so S3 saw one hot prefix, and almost all requests landed on one partition. Worse, the next night's IDs would start with different characters. The partitioning S3 had built up for one night's prefix would go cold, and the scaling would start from scratch every night.

The fix. A small, fixed set of prefixes: a digit from 0 to 9, a dash, then the file type (contract note data, temporary PDF or signed PDF). For example, 1-tmp-pdf and 7-signed-pdf. Requests spread evenly over 10 stable prefixes, multiplying the rate limit roughly tenfold. Because the prefixes are the same every night, partitions S3 creates stay useful. The team also asked AWS to pre-warm those partitions ahead of the bursty batch.

Overlooked constraints.

  • "Unique key" is not "spread key". Unique IDs avoid collisions but can still concentrate load if they share a prefix. Time-ordered IDs (KSUID, ULID, UUIDv7, Snowflake IDs) are great for database indexes and terrible as leading characters of S3 keys under burst load. See unique ID generation.
  • Retries amplify throttling. Ten retries on 503 add load on the already throttled partition. Exponential backoff with jitter is essential, and prefix design is the real fix.
  • Object storage latency is per request. For millions of small files, request count and per-request latency matter more than bandwidth. That is the opposite of the large-blob case in handling large blobs.

What Zerodha sacrificed. The lowest latency (EBS was 10 times faster) for shared access and cost. Some key randomness, since fixed prefixes do not use an ID's natural order. And a dependency on AWS's internal partitioning behaviour, which needed a support conversation to understand.

Deep Dive: prefix arithmetic for a bursty batchShow

Demand (handbook's illustration). 7 million files are each written once and read once or twice, for about 7 million PUTs and 10 million GETs in about 20 minutes of active work. Averaged, that is about 5,800 PUTs and 8,300 GETs per second. Bursts at stage boundaries can be 2 to 3 times higher.

One prefix. Capacity is 3,500 PUTs and 5,500 GETs per second. Average demand is already 1.7 times the PUT limit and 1.5 times the GET limit, so throttling is certain.

Ten prefixes, evenly loaded. Capacity is 35,000 PUTs and 55,000 GETs per second. Average PUT load is about 17 percent of capacity and bursts about 50 percent. That leaves headroom, provided partitions are already split (pre-warmed). Otherwise S3 must split them during the burst, which takes time.

Choosing the prefix. Use a stable hash of the client ID mod 10, not a random number, so retries and the next stage compute the same key. The type after the digit keeps different stages from competing for the same prefix. With 3 file types, there are 30 prefixes in total.

Lesson 15: The ephemeral Nomad cluster and high-throughput email (2024)#

Assumptions. The batch runs once a night, needs about 40 large machines for under half an hour, and should leave nothing running afterwards. Zerodha already deploys services with HashiCorp Nomad, so the team knows it well. The post finds it far easier to run than Kubernetes.

Provisioning. Every midnight, a Terraform module builds a fresh Nomad cluster, with servers and clients, from scratch. The module creates launch templates, auto scaling groups (ASGs), IAM roles and security groups. There is one ASG per worker role (PDF generation, signing, email), so each can be sized independently. PDF generation needs far more CPU than signing.

Control. A small, long-lived control instance runs Rundeck, which orchestrates the night in three phases:

  1. Initialise. Run the Terraform pipeline and wait until every Nomad client is eligible for scheduling.
  2. Deploy jobs. Nomad starts the worker programs, mostly Go binaries pulled from S3, on the right nodes. The workers then listen to the Tasqueue broker.
  3. Tear down. A watcher program tracks the count of successful jobs in Redis. When everything is done, it runs Terraform's teardown. ASG counts go to zero, nodes are drained, Nomad jobs stop and the Nomad servers shut down.

Rundeck also shows job status pulled from Redis, so an operator can watch progress.

Scheduling. Nomad system jobs run exactly one instance of a task on every eligible node, like a Kubernetes DaemonSet. A constraint limits each task group to nodes with a matching role. Terraform writes each instance's EC2 role tag into the Nomad client's metadata, and the job specification says, for example, "run the PDF creator only where the role is worker-pdf". Each worker process then uses all the cores of its node through concurrency.

Scale and result. About 40 instances: a mix of c6a.8xlarge, c6a.4xlarge and c6a.2xlarge (AMD compute-optimised). End to end, 25 minutes. Cost is negligible.

Email. Signed PDFs are queued for email immediately. Email workers keep pools of concurrent SMTP connections, using the team's smtppool library, to a self-hosted, auto-scaling Haraka SMTP cluster. Haraka (a Node.js SMTP server) replaced Postal, which used a lot of resources and could not scale horizontally. Haraka scales out easily. Deliverability depends on IP reputation, which Zerodha has built over almost a decade by never sending marketing email or spam. Lesson 22 shows the same principle as a product choice.

A reusable pattern. The post notes that this is not one big system but a set of small scripts and programs. Each building block (Rundeck, Nomad, S3, Redis) could be swapped. The team planned to move other heavy nightly jobs onto the same framework and to add live metrics from workers.

A sketch of the role-to-node mapping (handbook's illustration, in YAML for clarity; Nomad itself uses HCL):

cluster: contract-notes-nightly
lifetime: ephemeral            # created at midnight, destroyed on completion
roles:
  worker-pdf:
    instance_types: [c6a.8xlarge, c6a.4xlarge]
    desired: 24
    job_type: system           # one worker process per node
  worker-signer:
    instance_types: [c6a.4xlarge]
    desired: 10
    sidecar: openpdf-signer-jvm
  worker-email:
    instance_types: [c6a.2xlarge]
    desired: 6
teardown:
  trigger: redis_success_count == expected_jobs
  action: terraform_destroy

Overlooked constraints.

  • Fresh clusters every night mean fresh failure modes every night. AMI changes, capacity shortages for a given instance type in the region, or Terraform drift can stop the job from starting. Instance-type fallbacks in the ASG (override instance types) reduce the risk.
  • Email is not done when SMTP accepts it. Recipient servers can defer or bounce. Bounce handling and retries extend beyond the 25-minute run, so the SMTP cluster may need to outlive the compute cluster.
  • A single Redis is a single point of failure. If it dies mid-run, job state is lost. Because the batch is idempotent per client and can be rerun for the missing ones, this is acceptable.

What Zerodha sacrificed. Always-on readiness: the cluster does not exist during the day, so an urgent re-run means waiting for provisioning. It also gave up Kubernetes's larger ecosystem, accepting Nomad's smaller one for its simplicity. See containers and Kubernetes and long-running tasks.

Deep Dive: email throughput and connection poolingShow

Rate needed (handbook's illustration). 1.5 million emails in about 15 minutes of the run is about 1,700 emails per second. Each email with a 150 KB attachment is about 200 KB once base64 encoding adds a third. That is roughly 340 MB per second, or about 2.7 Gbit/s outbound. That needs several SMTP nodes simply for bandwidth.

Connection reuse. Opening an SMTP connection costs a TCP handshake, TLS negotiation and the SMTP greeting, perhaps 50 to 100 ms. Sending a message on an open connection costs mostly the data transfer. A pool of persistent connections from each email worker to the Haraka cluster avoids repeating the setup 1.5 million times. It is the same idea as database and HTTP keep-alive pools in Lesson 5.

Reputation as capacity. Large mailbox providers throttle or junk mail from IPs with poor reputation, regardless of how fast you can send. A broker that sends only transactional mail (contract notes, OTPs and statements) keeps complaint rates near zero, which is why it can push this volume from its own IPs. A company that mixes marketing into the same IPs risks its regulatory mail landing in spam.

Family 5: Observability on a budget

Lesson 16: Logging: from ELK to Vector, ClickHouse and Metabase (2023)#

Assumptions. Zerodha runs many internal and public services that produce a lot of logs. Developers use them to debug. Some services emit logs that regulation requires to be retained for years. The assumptions:

  • Volume. Tens of billions of log lines retained, growing with traffic. Peak volume follows market hours.
  • Queries. Mostly filters by time, service, level and a few fields, plus aggregations over days or months. Full-text search on every field is rarely needed.
  • Access. Developers and business teams both query logs, with different permissions: a developer who owns one app should see only that app's logs.
  • Cost. Multi-year retention makes storage per log line the dominant cost.

ELK and its problems. From 2018, Filebeat on each EC2 instance shipped logs to a central Logstash server. Logstash added metadata, scrubbed sensitive data and parsed lines, then wrote them into Elasticsearch indices queried with Kibana. A single Elasticsearch node, on a large instance because of JVM memory needs, worked when traffic was a tenth of what it later became. After 2020 it struggled:

  • Logstash slowed down at peak, delaying ingestion.
  • Storage grew at least 3 to 4 times the raw log size, because every field was indexed for search.
  • Querying with Lucene syntax or KQL was unintuitive.
  • Aggregations over long periods were slow.

Until 2021 the team threw hardware at the problem while researching alternatives.

Alternatives rejected.

  • Grafana Loki 0.4 (late 2019): young, few storage options and a complicated microservice deployment.
  • Loki 2.4 (2021): much simpler to deploy, but a month of Kite logs made queries painfully slow, most timed out, and the open-source version lacked good role-based access control (RBAC).
  • cLoki (Loki's API on ClickHouse): did not use ClickHouse's native compression codecs, did not allow custom schemas, partitions, TTLs or ordering keys, and was slow on partial matches.

Loj: Vector, ClickHouse and Metabase. The internal name is "Loj". The back-office team was already using ClickHouse as a warehouse for holdings and trade breakdowns, which gave confidence. Cloudflare's earlier write-up on storing HTTP analytics in ClickHouse also helped.

Why ClickHouse fits logs. ClickHouse is a column-oriented database for analytical (OLAP) workloads. Logs look like OLAP data: large batch inserts, rare updates, mostly immutable rows, and read queries that touch a few columns over many rows. Columns compress well with block-level codecs (LZ4, ZSTD and others), and LowCardinality columns are dictionary-encoded, storing small integers instead of repeated strings. Queries read only the columns they need.

Cluster. 2 shards, each with 2 replicas, for 4 nodes, coordinated by clickhouse-keeper (ClickHouse's built-in replacement for ZooKeeper).

Schema. Most apps share a standard app-log schema: timestamp, hostname, level, message, source and line, plus a free-form parameters field. HTTP access logs from HAProxy and Nginx use a separate schema with method, status, URI, client IP, bytes, user agent and user ID. SMTP and AWS Pinpoint logs have their own tables. Tables use the ReplicatedMergeTree engine, are partitioned by month or day, are ordered by timestamp (or type then timestamp for HTTP logs) and have TTLs. App logs keep 90 days by default, with shorter TTLs by level: debug lines are deleted after 15 days and warnings after 30.

A schema in the same spirit (handbook's illustration, not Zerodha's exact DDL):

CREATE TABLE logs.app_local (
  ts        DateTime64(3, 'Asia/Kolkata'),
  host      LowCardinality(String),
  service   LowCardinality(String),
  lvl       LowCardinality(String),      -- debug, info, warn, error
  msg       String CODEC(ZSTD(3)),
  params    String CODEC(ZSTD(3)),       -- logfmt or JSON key-values
  INDEX msg_tokens msg TYPE tokenbf_v1(10240, 3, 0) GRANULARITY 4
)
ENGINE = ReplicatedMergeTree('/clickhouse/tables/app/shard1', 'replica1')
PARTITION BY toYYYYMMDD(ts)              -- daily for high-volume apps
ORDER BY (service, lvl, ts)              -- low cardinality first
TTL toDateTime(ts) + INTERVAL 15 DAY DELETE WHERE lvl = 'debug',
    toDateTime(ts) + INTERVAL 30 DAY DELETE WHERE lvl = 'warn',
    toDateTime(ts) + INTERVAL 90 DAY DELETE;

Savings. On a benchmark of 65 million rows from one application:

StackDiskBytes per row
Elasticsearch22.1 GB340
ClickHouse1.13 GB17.38

That is a 20 times reduction. In production, about 30 billion lines in ClickHouse take about 2.5 TB, against about 13 TB for 28 billion lines in ELK. The ratio differs from the benchmark because real logs are more varied. Hardware fell too. The ClickHouse cluster runs on 4 r5a.2xlarge instances (8 cores, 64 GB) at about 1.14 dollars an hour, and the post says they are overpowered for the load. The ELK cluster had needed 3 m5a.8xlarge instances (32 cores, 128 GB) at about 2.67 dollars an hour, with five times the EBS volume.

Producing good logs.

  • App logs use logfmt, key=value pairs that are readable by humans and easy to parse. They are written by a zero-allocation Go logging library Zerodha built and open-sourced.
  • HTTP logs come from custom log templates in HAProxy and Nginx.
  • SMTP logs come from a Haraka plugin the team wrote to emit JSON with recipient, subject and SMTP response. Haraka itself had replaced Postal with about a tenfold gain in resource usage and throughput.

Vector. Vector, a Rust log shipper, replaced both Filebeat and Logstash.

  • Agent mode. Baked into every AMI, the agent collects logs from files or stdout and enriches them with the hostname and EC2 tags. It parses JSON or logfmt and ships to a central aggregator.
  • Aggregator mode. The aggregator buffers on disk and routes each event to the right ClickHouse table by a routing key set by the agent.
  • VRL. Transformations use VRL (Vector Remap Language): dropping health-check noise, coercing types (a status that will not parse becomes 0), and reshaping events into the target schema. A vrl command-line tool tests scripts, and "vector top" shows throughput and buffer use.

Metabase as the UI. Metabase provides SQL queries, saved query templates for non-technical teams (who picked up basic SQL) and RBAC. RBAC combines ClickHouse users and groups with Metabase database permissions. Gaps: no live tail, no easy "show the lines around this match" context view, and no time-slicing UI. The team also built a Go command-line tool, the Loj CLI, that turns flags (since 6 hours, filters, stats per minute) into SQL over ClickHouse's HTTP interface.

Hard-won ClickHouse lessons.

  • Partition key. Every partition and part has metadata and a location on disk. Too many partitions slow queries and use memory. High-volume apps whose queries span a few days use daily partitions; low-volume apps use monthly ones.
  • Too many INSERTs. Each insert creates a new "part", and background merges combine parts. In v1, every Vector agent inserted directly. At peak, the number of active parts in a partition hit ClickHouse's limit, merges could not keep up, and tables went read-only. The fix was to route agents through a Vector aggregator cluster that batches inserts.
  • Indexes. The primary key (sort order) cannot be changed after table creation, so choose it carefully. Data-skipping indexes add speed for other patterns: a bloom_filter index on client_ip for high-cardinality lookups, and a tokenbf_v1 token bloom filter on URIs for partial string matches.
  • Sort key order. Ordering columns from low to high cardinality usually speeds queries, because ClickHouse can binary-search the leading key and skip more granules.

Overlooked constraints.

  • Log search is not log analytics. ClickHouse is excellent at aggregations and decent at token searches, but it is not a full-text engine. Arbitrary substring search over months still scans a lot. Elasticsearch remains better for that pattern.
  • Schema discipline is required. The savings come from typed columns, LowCardinality and good sort keys. Dumping raw JSON blobs into one string column loses most of the benefit.
  • Batching adds delay. Aggregator buffers mean logs appear seconds after they are written, which matters during live incident debugging.

What Zerodha sacrificed. The polished log-exploration UI of Kibana: live tail, context lines and time drill-downs. Also schema flexibility, since new fields need table changes or a catch-all column. In return it got about 5 to 20 times less storage, cheaper nodes, SQL and proper RBAC. See observability and time series databases.

Deep Dive: why a column store compresses logs 20 times betterShow

Row store with inverted indexes. Elasticsearch stores each document (the source JSON) and builds an inverted index for every indexed field, plus doc values for aggregations. A 200-byte log line with 8 fields can easily become 500 to 1,000 bytes on disk, which matches the "3 to 4 times" figure and the benchmark's 340 bytes per row.

Column store. ClickHouse stores each column separately, sorted by the table's ORDER BY.

  • Level and service. In a level column with 4 distinct values, sorted runs of identical values compress to almost nothing.
  • Timestamps. A timestamp column sorted ascending, with delta encoding, takes a byte or two per row.
  • Hostname. As LowCardinality, it becomes a dictionary plus small integers.
  • Message. The message column is the bulk. ZSTD on similar messages, which are close together because of sorting, often reaches 5 to 10 times compression.

The total of about 17 bytes per row in the benchmark is the sum of these small per-column costs.

Parts and merges (handbook's illustration). If 2,000 agents each insert every second, ClickHouse creates 2,000 parts per second. Merges might combine a few hundred parts per second, so active parts grow without bound until the limit (a few hundred to a few thousand per partition, depending on settings) stops inserts. With 4 aggregators each inserting a batch of 100,000 rows every 2 seconds, only 2 parts per second are created, which merges easily absorb.

Cost per retained line. 2.5 TB for 30 billion lines is about 83 bytes per line in production, including replicas and varied schemas. At 0.08 dollars per GB-month for gp3 EBS, that is about 200 dollars a month for disk. At ELK's 13 TB, it would be over 1,000 dollars a month before compute.

Lesson 17: Infrastructure monitoring with Prometheus and VictoriaMetrics (2020)#

Assumptions. Zerodha's systems are spread across physical racks in two data centres, where exchange leased lines terminate, and AWS. Workloads range from bare metal to EC2 instances to several Kubernetes clusters. The assumptions:

  • Scale. Kubernetes alone, through kube-state-metrics, can produce hundreds of millions of active data points across clusters. Ingest is tens of thousands of samples per second.
  • Retention and HA. Metrics must outlive any single Prometheus node.
  • Maintenance. As few components as possible, managed by the same small team.

Prometheus. Chosen after evaluating Sensu, Nagios, ELK and others, for its multidimensional label model and its query language, PromQL. Example: summing the per-second request rate grouped by status code. Prometheus pulls metrics from targets, so it must discover them:

  • EC2. EC2 service discovery finds instances, and a relabel rule keeps only those tagged monitoring=enabled. AMIs are baked with Packer and include a standard set of exporters, so tagging a new instance is enough to monitor it.
  • Bare metal. Racks in the data centres have static IPs reachable over point-to-point leased lines to the AWS VPCs, so they use static target lists.
  • Kubernetes. Clusters run Prometheus through the Prometheus Operator, which manages Prometheus as a Kubernetes resource and handles creation, scaling and config reloads.

Long-term storage: Thanos rejected, VictoriaMetrics chosen. A single Prometheus's local storage is neither clustered nor replicated, so it is not durable or scalable on its own. The team wanted all Prometheus instances to push into one store with central retention, backups and snapshots, instead of scattered EBS volumes. Thanos needed too many components. VictoriaMetrics, then young, shipped as a single binary, used less RAM and disk in benchmarks, and was written by an author whose other Go projects the team already trusted. Prometheus writes locally and also forwards to VictoriaMetrics via remote write. Its local write-ahead log covers outages of the remote store for the local retention period. At the time of the post, VictoriaMetrics held about 56 billion data points after retention cleanups. It speaks the Prometheus query API, so Grafana uses it directly, and PromQL queries aggregate across clusters.

Configuration across clusters. Kustomize "base" and "overlay" layers (with a small tool, kubekutr, built around Kustomize) hold common config once and per-cluster differences separately. Overlays set the replica count, the remote write endpoint and the external Alertmanager. Each cluster's Prometheus adds an external label, zero_cluster, with the cluster's name, so identical metric names from different clusters stay distinguishable in the central store.

Alerting. One central Alertmanager cluster receives alerts from every Prometheus, deduplicates them and routes them. A small webhook bridge, calert, posts them to Google Chat. Rules and configs live in GitLab. CI lints them and uploads them to S3, and a sync process on the Alertmanager hosts reloads on change.

Custom exporters.

  • store-exporter runs SQL against Postgres or MySQL and exposes the results as metrics. This turns business numbers into Grafana panels and alerts on anomalies, for example when account openings or orders deviate from expected behaviour.
  • An embeddable HTTP exporter built on fasthttp exposes RED metrics (rate, errors, duration) for internal services. It uses the lightweight VictoriaMetrics metrics library, which has far fewer dependencies than the official client.
  • AWS exporters report AWS Direct Connect link health and bandwidth, and check EBS snapshot policies and backups.

The post adds that the team keeps dependencies in critical applications to a minimum and reviews them regularly. Grafana 6 sits on top with custom dashboards and stock ones for Postgres, HAProxy, Nginx and MySQL.

Overlooked constraints.

  • Cardinality is the real cost. kube-state-metrics and labels with user IDs or URLs can explode series counts. A single-binary store is simple, but it is still bounded by RAM per active series. Label discipline matters more than the choice of tool.
  • Pull needs reachability. Prometheus must reach every target. In a hybrid estate that means routing and firewall rules across leased lines, and a dead link looks like a dead host.
  • Business metrics from SQL load the database. store-exporter queries must be cheap and infrequent, or monitoring becomes the database's biggest client.

What Zerodha sacrificed. Thanos's object-storage-backed scale-out and global query view, and a vendor's managed monitoring. It accepted a then-young project (VictoriaMetrics) in exchange for one binary to run. It also accepted that single-node VictoriaMetrics is a single point of failure for history, though Prometheus's local WAL buffers short outages.

Deep Dive: sizing a metrics store and the label budgetShow

Series and samples (handbook's illustration). 600 hosts with node exporter expose about 1,000 series each, for 600,000 series. Three Kubernetes clusters with 2,000 pods and kube-state-metrics might add 1.5 million series. Application RED metrics with 50 endpoints, 5 status classes and 10 histogram buckets across 200 instances add 500,000 more. That is about 2.6 million active series. At a 30-second scrape interval, ingest is about 87,000 samples per second, the post's "tens of thousands" range.

Storage. VictoriaMetrics and Prometheus compress samples to roughly 1 to 2 bytes each. 87,000 samples per second is 7.5 billion samples a day, about 7.5 to 15 GB a day, or 2.7 to 5.5 TB a year. 56 billion points is about a week of this example's volume. Zerodha's retention policies decide how much history is kept.

Label budget. Adding a user_id label to a request counter with 1 million users multiplies series by up to 1 million. Keep per-user data in logs (Lesson 16), not metrics. Metrics answer "how many and how fast", logs answer "which one".

Family 6: Rules and clients

Lesson 18: Veto, and why a clever rule DSL lost to plain Go (2020)#

Assumptions. Every order a customer places must pass risk checks before it reaches the order management system (OMS), the vendor-built engine that talks to the exchange. The checks are written by the Risk Management (RMS) team, not by developers. Rules change often, sometimes within a trading day, when the exchange or the regulator changes a limit. Latency matters: an OMS has a queue, and every millisecond one order spends being validated is a millisecond added to every order behind it. Consistency is strict: a rule that is wrong lets a dangerous order through, and a rule that fails to load blocks trading.

The core problem is queueing. If the OMS evaluates 200 business rules for each order, its per-order service time grows, and by Little's law (Lesson 5) the queue in front of it grows with it. Zerodha's answer was to move business validation out of the OMS into a separate service called Veto. Veto is a reverse proxy, a server that sits in front of another server and forwards requests to it (see proxies and reverse proxies). It receives each order, runs the RMS team's rules, and either rejects the order on the spot with a reason or passes it through to the OMS. Rejected orders never touch the OMS, so the OMS spends its capacity only on orders that will probably be accepted.

The rules range from trivial to subtle. A trivial rule checks that a limit price is inside the day's circuit band, the maximum price move the exchange allows. A subtle rule blocks fresh buy orders in certain Nifty or BankNifty option strikes because the exchange has flagged them for open-interest (OI) limits, the cap on how many outstanding contracts may exist.

Version 1: an expression language. The first Veto grew out of an internal research project called Sentinel. Rules were written as Excel-like expressions and evaluated with the open-source Go library govaluate. A filter manager held the set of active rules and could hot-reload them, meaning swap in new rules without restarting the process. Operators edited rules in a dashboard built on Frappe, the Python framework behind ERPNext.

This looked ideal on paper. The RMS team writes rules, developers stay out of the way, and changes go live without a deploy. In practice it failed on human usability, not on speed:

  • Rules became unreadable. A real options rule turned into a wall of nested brackets. Operators spent hours writing one and developers spent hours reviewing it, because a misplaced bracket changed the meaning silently.
  • No branching and no variables. The language had only boolean operators and bracket grouping. There was no if/else and no way to name an intermediate value, so the same sub-expression was repeated many times.
  • Rules had to be split. One logical rule about option spreads had to be cut into four separate rules: call buy, call sell, put buy and put sell, because one expression could not express the branching.
  • Boolean only. A rule could say "reject" but not "reject because your spread leg is missing". Customers saw generic errors.
  • New functions needed developers. Any helper the expression language lacked, like "is this strike near the money", had to be written in Go and compiled into the engine. So developers were in the loop for every non-trivial rule, which defeated the purpose of having a DSL (domain-specific language, a small language made for one job).

This is a pattern worth naming: DSL creep. A team builds a small language so non-programmers can express rules. Users need more power, so the language gains features, one at a time, until it is a worse version of a real programming language with no debugger, no tests, no IDE and no community.

Benchmarking the options. Before rewriting, the team measured four ways to run rules, on the same sample rule (numbers from the post, nanoseconds per evaluation):

EngineWhat it isns per opDistribution
govaluateExpression parser and evaluator907Ship a string
Go native pluginsCompiled Go loaded as a shared library503Ship a compiled .so file
yaegiGo interpreter written in Go11,091Ship Go source
rego (OPA)Open Policy Agent's policy language13,796Ship a policy file

HashiCorp's go-plugin, which runs each plugin as a separate process and talks to it over RPC, was ruled out early because a network hop per rule is far slower than any in-process call. The table shows an interpreter costs 10 to 25 times more than compiled code. govaluate was fast but was the usability failure. Native plugins were the fastest and gave full Go, at the price of a harder build and distribution story.

Version 2: rules as Go plugins. In Veto v2 each rule is a small Go file compiled with -buildmode=plugin into a shared object, and Veto loads all of them at boot. A rule is a normal Go function, so it can use if/else, local variables, loops and helper functions. Each rule exports three functions:

// One rule file (handbook's illustration of the shape)
func Slug() string { return "spread_leg_required" }
 
func Validate(o Order) (Result, error) {
    if o.Segment != "NFO" || o.Side != "BUY" {
        return Result{Allow: true}, nil
    }
    if nearMoney(o.Strike, o.Spot) && !o.HasHedge {
        return Result{Allow: false,
            Message: "Fresh buys in this strike need a hedge leg"}, nil
    }
    return Result{Allow: true}, nil
}
 
// Built-in examples: input context mapped to expected result.
func TestData() map[string]Result {
    return map[string]Result{
        `{"segment":"NFO","side":"BUY","hedge":false}`: {Allow: false},
        `{"segment":"NSE","side":"BUY"}`:               {Allow: true},
    }
}

TestData is the clever part. Every rule carries its own examples, so the rule is self-testing and self-documenting. The build pipeline refuses to publish a rule whose examples fail. A reviewer reads the examples to understand intent without decoding the logic.

The plugin caveats, and how they were worked around. Go's plugin package is fast but famously fragile:

  1. Exact build match. A plugin must be built with the same Go version, the same versions of every shared dependency and even the same GOPATH layout as the host binary, or loading fails. Zerodha built plugins inside a pinned Docker image (golang 1.14 at the time) with mocked paths, so every plugin matched the host exactly.
  2. No shared host types without in-tree builds. A plugin cannot reference types defined in the host's main package unless built in the same tree. The fix was to put shared types like Order and Result in a separate package both sides import.
  3. No unloading, and no loading the same plugin twice. Once a .so is in memory it stays. Loading an identical file again is refused. So a "reload" would fail if the rule had not changed in a way that changed the binary.
  4. Under-loved feature. The plugin package gets little upstream attention, and Windows is not supported.

To deal with points 3 and 4, the team added a compilation step. Instead of one .so per rule, a compiler merges all rule files into one plugin. It parses each file into an abstract syntax tree (AST, the tree form of source code that compilers work on) and renames each rule's exported functions with a unique prefix, so Validate in file a_sample_rule becomes E_a_sample_rule_Validate. A step called AddTimestampToSource injects a unique constant into the source, so every build produces a binary that differs from the last and can always be loaded as "new". A generated description.go exports one Description() function listing every rule in the bundle, and the host's DecompileRules step reads it to find each rule's functions by name.

Operations. The Frappe panel gained a code editor. Saving a rule sends it to a validation server, which builds it with a timestamp, runs its TestData examples and returns the compiler or test output if anything fails. Approved rules go to a compiler server, which syncs all rules from the panel, builds the merged plugin, pushes it to the production Veto instances and triggers a hot reload. Both servers run on Zerodha's internal Kubernetes cluster.

The surprise was the people side. The RMS operators were not programmers, but they learned enough simple Go to write rules within a short time, because a rule is twenty lines of if-statements with good examples, not a general program. Trusting operators with a real language turned out better than building them a growing toy one.

Overlooked constraints.

  • The bottleneck was human, not CPU. v1 was fast enough. It failed on hours of authoring and review per rule. Benchmarks alone would never have shown that.
  • Memory grows with every reload. Because Go plugins cannot be unloaded, each hot reload leaves the old bundle in memory. Over a long trading day with many rule pushes, the process slowly grows until it is restarted, usually overnight. A team adopting this must plan restarts.
  • Fail-open versus fail-closed. If a new bundle fails to load mid-day, Veto must keep the last good rule set, not run with none (which would let every order through) and not reject everything (which would halt trading). The validation server exists precisely to catch failures before production.

What Zerodha sacrificed. The portability and safety of an interpreted or sandboxed policy engine like OPA. A Go plugin runs with full access to the host process, so a buggy rule can panic or leak memory inside Veto, and only review plus TestData stands guard. They also accepted a brittle build chain pinned to an exact toolchain, an upgrade of Go means rebuilding every rule, and a reliance on a little-maintained part of the Go standard library.

Deep Dive: what pre-validation saves the OMSShow

Load shed (handbook's illustration). Suppose 3 million orders arrive in the first 15 minutes of market open, about 3,300 per second. If 4 percent fail risk checks, Veto rejects 130 per second that the OMS never sees. The OMS also no longer evaluates business rules, so its per-order service time drops. If business rules took 200 microseconds of a 1 millisecond OMS service time, the OMS's capacity per core rises from 1,000 to 1,250 orders per second, a 25 percent gain on the most expensive, hardest-to-scale component (vendor software is licensed, not freely cloned).

Rule cost. At 503 ns per rule, 200 rules cost about 100 microseconds per order on one core, so one core handles about 10,000 orders per second. With govaluate the same rules cost 180 microseconds. With yaegi they would cost 2.2 milliseconds, which at 3,300 orders per second needs about 7 cores just to interpret rules, and adds 2 ms to every order's latency. This is why "just use an interpreter" was not chosen even though it is easier to ship.

Ordering rules. Cheap, high-rejection rules (circuit band, lot size) should run first so most rejects exit early. Expensive rules (anything needing position or OI lookups) run last. This is the same short-circuit logic a database query planner uses when it evaluates cheap selective predicates before expensive ones.

Where else this pattern appears. A pre-validating proxy is a general idea: an API gateway that checks auth and quotas before the backend (API gateway), a WAF that drops bad requests before the app, and a rate limiter that sheds load early. The principle is the same: reject as early and as cheaply as possible, so the expensive component only does work that will count.

Lesson 19: Native, then React Native, then Flutter, with two mobile developers (2015 to 2022)#

Assumptions. Kite's mobile app shows live prices for dozens to hundreds of instruments, updated several times a second, on phones that range from flagships to budget Android devices on flaky mobile networks. Roughly 90 percent of users are on Android and about 10 percent on iOS. The mobile team is tiny: one developer at first, two later, and still two as of the post. Features ship on the web first, where they are cheapest to fix, and reach mobile once the API and UX are stable. Correctness and responsiveness matter more than visual flourish, because users are placing money-moving orders.

Native Android (2015). Kite started as a web app built on the Kite Connect APIs. In 2015, when mobile trading in India was rare, a single developer with no prior mobile experience built a native Android app by trial and error, released in early 2016. For iOS, demand was small, so Zerodha shipped a thin native shell that wrapped the responsive web app in a webview, a browser component embedded inside an app. As features piled up, Android development slowed under device- and OEM-specific bugs, and iOS usage grew enough that a webview was no longer acceptable.

React Native (2017). React Native renders real native UI components but runs app logic in JavaScript, talking to the native side across a "bridge" that serialises messages between the two worlds. Zerodha chose it at version 0.42 because the result looked and felt native. The iOS rewrite took about 5 months, much faster than the original Android app, and iOS users liked it. Then the problems came:

  • Dependency chaos. Hundreds of thousands of files in node_modules, builds that broke for no visible reason and were fixed only by deleting and reinstalling everything.
  • A supply-chain scare. Someone uploaded a fake React Native build to JCenter, a public Android package repository, and Gradle preferred it over the official one, breaking builds worldwide. Zerodha was saved only by being on an older version. Anyone on the matching version could have shipped the fake library unknowingly. This is a real example of why pinning and verifying dependencies matters (see security fundamentals).
  • Third-party libraries. Even a native checkbox needed a third-party package, and every package had to be forked to upgrade Android SDK versions.
  • Upgrades almost never happened. Each attempt produced cryptic red-screen errors whose stack traces pointed into React Native's own native code, so the only debugging tool was deleting parts of the app until it launched.

The tipping point was live ticks on Android. Kite parses binary market data from a WebSocket many times a second, computes changes and renders numbers. On mid-range Android phones, React's batching of state updates, the cost of crossing the JS-to-native bridge, and the lack of a fast lazily rendered list combined badly. Prices lagged the native app by up to a second, or flickered unreadably when batched updates landed together. The team cut rendering down to the text element, tuned reconciliation (React's diffing of old and new UI trees), throttled updates to fixed intervals and pushed values straight to native views to skip React's state machinery. That got ticks to acceptable, but navigation, through a library that worked well on iOS, was buggy on Android. They abandoned the plan to replace native Android with React Native and kept it for iOS only, leaving two very different codebases to maintain.

Two things from this era stayed useful. The team wrote a small in-house library for state, networking, data unpacking and persistence to escape dependency sprawl, plus a navigation library that used only hardware-accelerated transitions. With those, the Coin mutual-fund app worked fine in React Native, because its screens do not stream live prices. And CodePush, which updates an app's JavaScript bundle over the air without an app store release, was valuable for emergency hot patches, except that on some devices its automatic rollback undid updates for reasons nobody could debug, which is the worst property for a tool you reach for only in emergencies.

The top path is React Native in 2017: two threads and a serialising bridge between data and pixels. The bottom path is Flutter: Dart code drives the engine that draws every pixel itself, with no bridge per update.

Flutter (2018). Flutter draws its entire UI on a GPU surface using its own engine, rather than wrapping the platform's native widgets, and runs app code in Dart, compiled ahead of time (AOT) to machine code for release builds and run in a JIT (just-in-time) VM during development for hot reload. In early 2018 it was alpha software. The concerns were real: a new language, a 5 MB hello-world app (versus kilobytes for native), a weak webview plugin, no large open-source Flutter app to learn structure from, and no runtime reflection in Dart, which broke the way their existing serialisers worked.

The decision process is the most transferable lesson:

  1. Months of low-stakes use. One developer built several personal projects in Flutter first, which built real intuition about where it was strong and weak.
  2. Explicit risk analysis. Kite is a critical financial app, and betting on alpha software could backfire if Google dropped it. The team reasoned that because Flutter was open source and already usable, even an abandoned Flutter would serve them for several years.
  3. A one-week prototype under stress. They built a fully navigable Kite UI with mock data and simulated market ticks in about a week, then stress-tested it. It handled the tick load easily. That prototype, not opinions, made the decision.

The rewrite. Starting mid-2018, they replaced native Android first, because it had the most users and the worst maintenance burden. Feature parity took about 3 months, helped by tools they wrote: a code generator (later published as dartgenerate) that produces serialisers, enum maps and asset embedding from annotations in place of reflection, and recharge, a hot-reload helper for Dart command-line tools. Kite 3.0 on Flutter shipped for Android in early 2019 and for iOS about 6 months later, finally retiring the React Native app.

Notable engineering inside the rewrite:

  • Custom widgets by copying source. When a built-in widget did not behave as wanted, they copied Flutter's own readable source, tweaked it and used the copy: tab views with different scroll physics, bottom sheets with arbitrary snap points, and a patched WebSocket with connection timeouts, essential on flaky mobile networks.
  • Charts in a webview overlay. Charting is web-based. Because Flutter paints everything on one surface, a native webview cannot simply be embedded. Before Flutter's Hybrid Composition existed, they overlaid a webview on top of the Flutter view with a Kite-specific hack.
  • Autopilot for black-box QA. Flutter had no Appium-style external driver. The team built Autopilot, a tiny web server inside test builds that exposes a JSON API to inspect and drive the widget tree, and a Python suite that runs many test cases against real devices without access to app source.
  • Accessibility. Built-in semantics for screen readers, plus an Accessibility Mode that turns off difficult gestures and transitions, which power users also like because it makes the app snappier.
  • Lean app and network. The Android APK for one architecture stays around 10 MB, through few dependencies, SVG graphics and no third-party analytics or marketing SDKs. Market data uses a compact binary WebSocket protocol, and repeated HTTP calls use ETag caching (Lesson 6). Some responses arrived faster than one display frame, which once exposed subtle async ordering bugs.

New framework, new problems. Flutter removed whole classes of bugs but brought its own:

  • Graphics stack failures. Because Flutter draws everything, a GPU driver or OS graphics bug can black out the entire app. Under 1 percent of Android users saw this at some point, fixed upstream over time.
  • Shader compilation jank on iOS. The first time an animation runs, its GPU shader must compile, which can take longer than the 16 ms frame budget at 60 frames per second. Android caches compiled shaders across launches, iOS (at the time) did not, so the first transition after every launch stuttered. Kite's answer was mostly to keep animations minimal, which suits a screen of numbers anyway.
  • Native library extraction. Loading Flutter's shared libraries directly from the APK, which saves disk, crashed on some Xiaomi phones running Android 6, so the feature had to be disabled.
  • Biometrics. Older Android versions report fingerprint support inconsistently, and the official plugin could not enforce strong biometrics, so Zerodha maintains a fork.
  • High refresh rate. Flutter apps did not run at 90 or 120 Hz by default. The flutter_displaymode plugin fixed fixed-mode OLED panels, but adaptive LTPO panels need engine-level support.
  • HTTP/1.1 only. Dart's standard HTTP client lacked HTTP/2 and ALPN (the TLS extension that negotiates the protocol), and had no HTTP/3 plans. Zerodha built flutter_curl, which calls a trimmed libcurl through Dart's FFI (foreign function interface, calling C libraries from Dart) for HTTP/2 with ALPN and Brotli compression. They considered Cronet, Chrome's network stack, which has HTTP/3 and built-in caching, but chose curl for its small size and configurability. See HTTP and HTTPS for why multiplexing matters on high-latency mobile links.

Overlooked constraints.

  • Team size is a hard constraint. Two developers cannot maintain three codebases (Android, iOS, web) at parity. The real requirement was one mobile codebase, and performance was the filter on which one.
  • The hardest screen decides. React Native was fine for Coin and for iOS. The live tick screen on budget Android was the case that broke it. Evaluate frameworks on your hardest screen and weakest device, not the average.
  • Owning the rendering means owning its bugs. A framework that draws every pixel is immune to OEM widget quirks but exposed to GPU driver bugs, shader compilation and missing platform features like refresh-rate control.

What Zerodha sacrificed. Native look and feel by default, since Flutter widgets imitate the platform rather than being it. A larger base binary (several MB for the engine and Unicode data). The comfort of a mainstream language and ecosystem in 2018, when Dart was niche. Seamless embedding of native views, which forced the webview overlay hack for charts. And ongoing ownership of forks and plugins (biometrics, display mode, curl) that a bigger team might have waited for upstream to provide.

Deep Dive: a tick-rendering budget on a budget phoneShow

The frame budget (handbook's illustration). At 60 Hz a frame is 16.7 ms. A watchlist screen shows 40 instruments, and during a busy market each instrument may tick 2 to 4 times a second, so 80 to 160 tick messages arrive each second, 1.3 to 2.7 per frame. Each tick needs parsing (a few microseconds for a fixed binary layout), computing change and percent, and re-laying out one text widget.

Where the bridge hurt. In a bridged architecture, if every tick becomes a JSON message across the bridge costing, say, 0.3 ms on a slow phone, 160 messages cost 48 ms per second of bridge time on top of JS work and native layout. That alone is not fatal. The real damage is contention: the JS thread also handles touches, navigation and state, so when a transition runs, tick updates queue, and React's batching then flushes several at once. Users see stale numbers, then a burst.

Coalescing. A robust design coalesces per instrument: keep only the latest tick for each instrument and render once per frame, so 160 ticks a second become at most 40 updates per frame, and usually far fewer, since only changed rows repaint. Dropping intermediate ticks is safe for display because users read the latest price. It is not safe for anything that computes from every tick, like a chart's candles, which should be built server-side.

Binary protocol arithmetic. A JSON tick with field names can be 200 to 400 bytes. A fixed-layout binary tick with instrument id, last price, volume and a few prices as 4-byte integers fits in about 44 to 184 bytes depending on depth. For 160 ticks a second, that is 7 to 30 KB per second versus 32 to 64 KB per second, which matters on a 2G or congested 4G link and on data-capped plans. See real-time communication for WebSocket trade-offs against SSE and polling.

Family 7: Platform, product and people

Lesson 20: Kite Connect, an accidental platform from one clean API (2014 onward)#

Assumptions. In 2014 the tech team had four or five people and no capital-markets experience. The OMS vendor exposed order functions through SOAP-like HTTP/XML APIs with inconsistent route names, inconsistent field names and thin documentation. The vendor's own white-label web platform was poor. Online account opening was not even legal in India until 2017: opening a broker account meant printing, signing and couriering a form of about 40 pages. Nobody in the industry offered a public trading API, and starting a new brokerage was (and is) very hard because of regulation.

The middleware. To build Kite web, the CTO spent weeks wrapping the vendor calls one at a time behind a Python web server that exposed clean HTTP/JSON endpoints with consistent naming. This is the anti-corruption layer pattern from domain-driven design: a translation boundary that stops a messy external model from leaking into your own code. The frontend developer could then build against a stable, readable API instead of the vendor's quirks. Getting the vendor's upstream APIs fixed took months, and incremental improvements took years, but the wrapper meant Kite did not have to wait.

The accident. The team noticed their wrapper API was generic enough to power any trading app, not only Kite. So, while Kite itself was still being built, they gave it a name (Kite Connect), designed an OAuth-like login flow so third-party apps could act for a user without ever seeing the user's password, wrote proper documentation and built a self-service developer portal. The post stresses this only happened because technical people held the decision rights: no business case would have justified a developer portal in an industry still couriering paper forms.

Brokerage as a Platform. The first big user was smallcase, which wanted to build thematic investment baskets. Zerodha gave them API keys, help with regulatory approvals and seed money. Zerodha's existing customers could log in to smallcase in one click, while Zerodha kept handling compliance, settlement, financial processes and infrastructure, and smallcase focused on product. That deal started Rainmatter, Zerodha's fintech investment fund, and turned Kite Connect into "Brokerage as a Platform": fintechs build on a licensed broker's rails instead of becoming brokers themselves. Today many apps and several companies run on it. Zerodha dog-foods it, meaning its own apps and internal systems use the same API. Kite Connect is a profitable business on its own, and those profits help fund the Rainmatter Foundation's environmental work.

Stable interfaces as the real asset. The future-ready post (Lesson 3) generalises this. "API" here means any boundary that makes promises: an HTTP API, a file or wire format, a CLI, an RPC or an ABI. When business change forces a rewrite, a stable interface is what lets one part be swapped without breaking its dependents. The post warns against treating internal APIs as cheap to change: internal integrations often get less design care than public ones, and that is exactly how they turn into technical debt. Getting the spec right early pays off even for internal systems. It also points out that modularity, meaning clean separations inside and between programs, is commonly confused with microservices. You can have the first without the second (see monolith vs microservices).

The sequence shows the shape of an OAuth-like flow (handbook's illustration of the general pattern; the exact Kite Connect parameters are in its public docs). The user's password only ever goes to Zerodha. The third-party app gets a short-lived token, proves it is the registered app by signing the exchange with its secret, and receives a session-scoped access token. See authentication and authorization for OAuth 2.0 details.

Overlooked constraints.

  • A public API freezes your mistakes. Once third parties depend on a field name or an error format, changing it breaks them. Dog-fooding helps because the team feels every rough edge first, but versioning and deprecation discipline become permanent work (see API design).
  • Liability does not move with the code. smallcase builds the product, but the broker remains the regulated entity. Every third-party app's orders still flow through Zerodha's risk checks (Lesson 18) and compliance, so the platform must protect itself from partners' bugs with rate limits and per-app controls.
  • Vendor quirks never fully disappear. The wrapper hides them, but it must still map every new vendor behaviour, error and outage into the clean model. The anti-corruption layer is a component that needs an owner forever.

What Zerodha sacrificed. Exclusive ownership of the customer experience: users can trade through apps Zerodha does not control, and their mistakes or outages reflect on the broker. Freedom to change APIs at will, since thousands of external integrations now depend on them. And engineering time in 2014 and 2015, spent on documentation and a developer portal when the team was tiny and building its own flagship product.

Lesson 21: Open source as a habit, and Alar, a dictionary from a stockbroker (2020)#

Assumptions. A small team writes many small internal tools to avoid paying for, or being trapped by, vendors. Most of these tools are not core trading logic, so there is little competitive risk in publishing them. Open-sourcing costs some effort (docs, issues, releases) but brings outside users who find bugs, plus credibility that helps hiring.

The projects. Zerodha publishes its free and open-source (FOSS) work on zerodha.tech, mostly in Go, with some Rust, usually under AGPL v3 or MIT. A selection (star counts from the project page when fetched, late 2026):

ProjectWhat it doesWhere this page covers it
listmonk (about 24,500 stars)Self-hosted newsletter and mailing-list manager, single binaryLesson 15 email context
dungbeetle (about 1,300 stars), formerly sql-jobberDistributed job server for heavy SQL reports, separates reporting from appsLesson 11
blobasaur (about 500 stars)Blob store on SQLite that speaks the Redis protocolLesson 12
hedwigMinimal, fast SMTP server in RustLesson 15
kaf-relayReplicates Kafka topics between clusters with failoverLesson 3 Kafka bus
otpgatewayOTP and address verification with pluggable providersLogin and onboarding
calertSends Prometheus Alertmanager alerts to Google ChatLesson 17
logchefLog analytics over ClickHouse, VictoriaLogs and LokiLesson 16
libredeskSelf-hosted customer support deskSupport tooling
store-exporterExposes metrics from arbitrary data stores to PrometheusLesson 17
csvtotable, stuffbinSmall utilities: CSV to searchable HTML, embed files in Go binariesDeveloper tooling
koanf, fastglue, simplesessions, simples3, TasqueueLibraries for config, HTTP handlers, sessions, S3 access and task queuesLessons 7 and 13
autopilot, flutter_curl, flutter_displaymode, dartgenerateFlutter toolingLesson 19

The pattern behind the list: when Zerodha needs something, the first question is whether a small, single-binary tool it understands completely would do. If yes, it builds one, runs it in production (dog-fooding) and publishes it.

Alar. The most unusual project is not technical at all. In 2018 a new engineer overheard the CTO, again, wishing for an open Kannada dictionary, and mentioned that a relative had worked on a dictionary for decades. The relative, V. Krishna, had spent more than 40 years writing a Kannada-English dictionary: over 150,000 Kannada words and 240,000 English definitions, with parts of speech and phonetic notation, all typed into a Word document using the old ASCII-encoded Nudi font. Zerodha gave V. Krishna a grant (and one to KaGaPa, the body behind Nudi) and a perpetual monthly stipend to keep working on dictionaries, and published the dictionary as open data under the ODbL licence at alar.ink in September 2019. It is believed to be the first authoritative dictionary open-sourced by its own author.

The engineering is a neat search problem:

  • Encoding conversion. The Nudi ASCII text had to be mapped to Kannada Unicode with scripts and heuristics, then structured into a spreadsheet the author could keep editing.
  • Phonetic hashing. Typing Kannada on phones produces many spelling variants. KNPhone, a port of MLPhone (built for the CTO's Malayalam dictionary Olam), turns a word into a key that encodes how it sounds, so variants collapse to one key. The post's example turns ಅಂಕೆಸಂಖ್ಯೆ into A3KS3KY. This is the same idea as Soundex or Metaphone for English names.
  • A language-agnostic engine. Any dictionary is "find this string in a set of strings". Only tokenisation, turning input into search keys, is language-specific. dictmaker standardises layout, pagination and rendering, and lets each language plug in its own tokeniser.
  • Transliteration suggestions. Using varnam, a user types Kannada in Latin letters ("hesaru") and gets ಹೆಸರು suggested.

Olam, the Malayalam dictionary behind these techniques, has answered lookups in about 50 ms since 2010, and its Datuk corpus holds about 200,000 entries, cleaned over two years from an RTF file a retired volunteer had posted online.

Overlooked constraints.

  • AGPL is a deliberate choice. AGPL requires anyone running a modified version as a network service to publish their changes. It protects against a cloud vendor offering the tool as a paid service without contributing back, but it also keeps some companies from adopting it at all.
  • Open source creates support load. Issues, pull requests and security reports arrive from strangers. A small team must decide how much time to give, or popular projects become a second job.
  • Search for non-English scripts needs language-aware keys. A plain Unicode substring match fails on Indic input because of spelling variation and input-method quirks. The tokeniser is the whole product.

What Zerodha sacrificed. Engineering hours on tools that, in the narrow sense, a vendor could have sold them. Some control: once published, a tool's direction is shaped partly by outsiders. And for Alar, money and time spent on something with no business return at all, a choice that only a profitable, founder-led, bootstrapped company can make freely.

Lesson 22: User disengagement, product design that refuses to maximise attention (2022)#

Assumptions. Zerodha earns money when users trade. A conventional growth team would therefore maximise sessions, notifications and trades. The CTO argues that "engagement" usually means pulling users back to a screen when they have no need, and calls the opposite approach user disengagement: build what is useful, and let people leave when they are done.

The philosophy rests on two rules: only do what is truly useful to users, and don't do to others what you would not want done to you. It is not about pushing users away; it is about removing screen time as a goal. Concretely:

  • No advertising. No online or offline ads, no paid placements, no marketing team, zero marketing spend. Growth comes from word of mouth, which forces the whole company to focus on products good enough to recommend.
  • No pushing. No promotional emails, SMS or notifications. Push notifications are used sparingly and never to "re-engage". No "rate this app" popups. No outbound calls except rare serious account matters or a requested callback.
  • No engagement tracking. User behaviour is not mined or profiled, and nothing is done to win back inactive users.
  • No gimmicks. No signup freebies or limited-time discounts, and a deliberate effort not to build "cool" features that are really gimmicks.
  • Meaningful friction. A small sign-up fee filters out people without real intent. A Nudge system across the apps warns users, and sometimes blocks them, before trades it judges risky, even though Zerodha loses the brokerage on those trades. A Kill Switch lets users lock themselves out of trading for a chosen period, which many users find valuable. Account closure is instant and online, including legal formalities.

The post ends by asking for common-sense human-computer interaction (HCI) principles over endless A/B tests that optimise "conversions".

The system-design reading. Product philosophy shows up as architecture:

  • Fewer systems to run. No ad tech, no engagement pipeline, no user profiling store, no campaign engine, no notification scheduler for marketing. Each absent system is one less thing to secure, scale and staff. This is part of how a small team stays small.
  • Lean clients. No third-party analytics SDKs in the apps (Lesson 19), which keeps the APK around 10 MB, reduces data leaving the device and removes a whole class of supply-chain risk.
  • User-controlled safety as a feature. The Kill Switch is a per-user rule in the order path, the same place Veto's risk rules sit (Lesson 18). Nudges are a soft version: a rule that returns "warn" rather than "reject", which is exactly why Veto v2 needed custom messages, not just booleans.
  • Privacy by absence. Data never collected cannot leak, cannot be subpoenaed in bulk and needs no retention policy (see data lifecycle and retention).

Overlooked constraints.

  • This needs a viable business model first. Zero marketing works because brokerage fees on real trades fund the company and users bring other users. A product without revenue per use cannot afford to ignore engagement.
  • Nudges are hard rules with false positives. Blocking a legitimate trade angers an experienced user. The rule set must be explainable, and the "warn" path must let informed users proceed.
  • You lose a feedback channel. Without behavioural analytics, product decisions rely on support tickets, forums, domain expertise and intuition, which the post accepts openly.

What Zerodha sacrificed. Short-term revenue, every time a nudge stops a trade or a user locks themselves out. Faster growth that paid acquisition might have brought. Quantitative product insight from tracking and A/B tests. And it accepted a slower, steadier growth curve in exchange for users who stay and recommend.

Lesson 23: The remoteness of remote work, an org-design lesson (2024)#

Assumptions. Capital markets are synchronous: exchanges open at fixed times and process orders in sequence, and settlements, reports and batch jobs (Lessons 13 to 15) must finish in the hours before the next market open. Incidents need many teams in real time. The tech team speaks about ten native languages, and English is a third or fourth language for most. The company has about 1,000 employees and a tiny tech team that had sat together for most of a decade.

What happened. In March 2020 Zerodha went fully remote overnight. The technology made it easy: zero-trust access with VPN, SSO and 2FA (Lesson 2), cloud telephony for support and online internal processes. The first year was intensely productive, during a trading boom. By the second year the novelty faded, and by the third, remote work was hurting creativity and collaboration:

  • Async does not fit a sync business. Open-source-style async work, where people reply when they can, works for open source but not for an organisation whose core work runs to the exchange's clock. The post warns that developers often wrongly generalise pull-request-style async workflows to the whole organisation.
  • Text chat favoured fast typists. In a multilingual team, people who type quickly in English dominated chat. Others' voices faded into terse, task-only messages, and misread emojis occasionally changed the direction of work.
  • Tools mattered. Self-hosted Mattermost worked well for chat. Matrix clients were a disaster for usability. Google Meet was passable for video. An org-wide self-hosted Discourse forum thrived for a while and then caused forum fatigue from too many threads.
  • Institutional memory cannot be fully written down. Rules, processes and systems can be documented, but much of what makes an organisation work lives in people and conversations. The CTO came to see "document everything" as a pipe dream.
  • The human cost. Isolation hurt mental wellbeing, and the CTO ended up doing near-weekly counselling-style one-to-ones, which led to burnout.

The fix: targeted hybrid. After months of debate and a majority consensus, about 10 percent of the company (around 100 people in tech, creative, business and key decision-making roles) returned to the office on Tuesday, Wednesday and Thursday. The other 90 percent, including the large support team, stayed remote, though a couple of hundred chose to come in. Office staff also get a fixed annual quota of work-from-home days to plan around. Within a couple of months, decisions that had taken days online took minutes. A September 2024 update reported about 90 percent of the team doing well mentally, against about 80 percent not doing well the year before.

The post lists the skills long-term remote work needs, which Zerodha had never hired for: fast and expressive written communication, being conversational beyond tasks online, digital etiquette, remote coordination, patience for writing lots of documentation, and the ability to focus productively alone.

Why this belongs in a system design handbook. Conway's law (Melvin Conway, 1968) says systems mirror the communication structure of the teams that build them. A team that can talk instantly can keep a modular monolith coherent and run tightly coordinated migrations. A team that communicates in slow, lossy text drifts toward rigid interfaces and more process. Zerodha's architecture of few large, well-understood systems, owned by two to four principal developers each, depends on dense, fast communication. Incident response (see incident management and postmortems) is the extreme case: a synchronous, cross-team activity where every minute counts.

Overlooked constraints.

  • The infrastructure was ready before it was needed. Remote work was technically trivial because of zero-trust access decisions made in 2017. Organisational readiness was the bottleneck, not technical readiness.
  • Commuting is a real cost. In Bangalore commutes are notoriously bad, so the 3-day schedule was a cost accepted deliberately, not a free choice.
  • Hiring shapes what works. An organisation hired for in-person collaboration cannot become remote-first just by changing policy. The skills must be in the people.

What Zerodha sacrificed. Some of the flexibility of fully remote work, which a minority wanted to keep. The option of hiring tech staff anywhere in the world without relocation. And some people's comfort: the post admits there was heartache among a few. It accepted those costs because, for a synchronous, conversation-driven organisation, the measured gains in speed and wellbeing outweighed them.

Family 8: Synthesis

Lesson 24: The trade-offs of boring technology, read across all the posts#

Assumptions. The reader has seen the 23 lessons above. The question now is what pattern they share, what it costs, and when it would be the wrong choice.

Across all the posts, a handful of moves repeat:

PatternWhere it appearsWhat it buysWhat it costs
Boring, proven tech (Postgres, Redis, Go, Kafka)Lessons 2, 4, 9Known failure modes, deep docs, easy hiring of skillsFewer built-in managed features, more self-operation
Self-host FOSS instead of SaaSLessons 2, 3, 16, 17Very low IT cost, no lock-in, control for complianceStaff time on upgrades, backups and on-call
Vertical scaling firstLessons 7, 9Simplicity, no distributed consistency issuesBigger blast radius per machine, hard ceiling
Precompute and cache hot resultsLessons 6, 11Millisecond reads under load spikesStaleness, cache warm-up and invalidation logic
Partition by a natural business keyLesson 10 (financial year)Small active data set, cheap archivalCross-year queries need federation
Build small single-binary toolsLessons 11, 12, 13, 21Exact fit, easy deploy, open-source goodwillMaintenance burden on a tiny team
Wrap vendors behind clean APIsLessons 18, 20Isolation from vendor quirks, platform optionalityA translation layer to own forever
Measure before choosingLessons 12, 14, 18, 19Decisions grounded in numbers from your workloadTime spent benchmarking up front
Ephemeral infrastructure for burstsLesson 15Pay only during the batch windowProvisioning must be reliable under a deadline
Product restraintLesson 22Fewer systems to build and secureLess growth tooling and data

The cycle is the CTO's "scaling with common sense" in one picture. It differs from the cloud-native default, where the first answer to a bottleneck is to add a managed service. At Zerodha the first answer is to understand the bottleneck, then pick the smallest change that removes it.

Why it works for Zerodha specifically. Four conditions make the approach pay off, and a reader should check them before copying it:

  1. The workload is bounded and predictable. Indian market hours are fixed, about 9:15 to 15:30 on weekdays. Peaks come at open and close. There is no global follow-the-sun traffic. Capacity can be planned with margin rather than elastically scaled.
  2. The team is senior and stable. A few principal developers own each system for years. Self-hosting requires people who know Postgres's vacuum, Redis's memory model and Kafka's retention by heart.
  3. The business is profitable and bootstrapped. No investors push for growth at any cost, so rewrites, open-source projects and product restraint are affordable.
  4. Regulation rewards control. Data residency, audit trails and access control are easier to prove when you own the servers and the code.

When the same approach would fail. A startup with spiky global traffic, a junior team, venture-funded growth targets or no ops experience would find self-hosting expensive in the currency that matters most to them: time. Managed databases, queues and observability let such a team spend its scarce engineers on the product. The lesson from Zerodha is not "never use SaaS" but "know what you are paying for, and own what is core to you".

What Zerodha sacrificed overall.

  • Elasticity. Vertically scaled, self-managed systems cannot double capacity in minutes the way a managed autoscaling service can. Zerodha relies on headroom and planning instead.
  • Off-the-shelf breadth. Every capability a managed platform bundles, like point-in-time restore, global replication, built-in dashboards and IAM integration, must be assembled or skipped.
  • Bus factor. Small teams with deep ownership mean that knowledge is concentrated. Lesson 23's point about institutional memory is also a risk statement.
  • Fashion. Zerodha passes on whatever is new unless it proves itself on their workload. They adopted Flutter early (Lesson 19) only after a prototype proved it. That caution sometimes means waiting longer for real improvements.
Deep Dive: a cost model for self-hosting versus managed servicesShow

A rough comparison (handbook's illustration, not Zerodha's numbers). Suppose a team needs a Postgres cluster with 2 TB of data, 64 vCPUs and 512 GB of RAM, plus one replica.

  • Managed. A large managed instance of this size with a replica and provisioned storage might cost on the order of 15,000 to 25,000 US dollars a month at list price, depending on provider and storage type.
  • Self-hosted on VMs. Two equivalent VMs with local or block storage might cost 5,000 to 9,000 dollars a month. Add backups to object storage and monitoring, which are cheap.
  • The hidden cost. Self-hosting needs perhaps a quarter of a senior engineer's time for upgrades, failover drills, backup restores, tuning and on-call. At a fully loaded cost of 8,000 to 15,000 dollars a month for that engineer in India, that is 2,000 to 4,000 dollars a month.

In this illustration self-hosting saves roughly 8,000 to 12,000 dollars a month for one cluster. Multiply by dozens of systems and the savings become material, but only if the engineers exist and are good. If the team has to hire specifically to self-host, or if one bad restore loses a day of trades, the comparison flips.

The break-even rule of thumb. Self-host when the system is core to the business, the team already has the skills, the load is steady enough to buy fixed capacity, and the managed premium exceeds the fraction of an engineer it would take to run it. Use managed when any of those is false, especially the second.

Cross-cutting: classic interview topics seen through Zerodha#

The reference material behind this handbook (the System Design Primer, Hello Interview's guides and the awesome-system-design list) covers a few general topics that Zerodha's posts illuminate from a practical angle.

Networking essentials in a trading system. Kite's paths touch most of the networking fundamentals:

  • Ticks over WebSockets. The ticker streams binary market data to clients over long-lived WebSocket connections, which run over TCP. TCP's ordered, reliable delivery suits prices, where a missing or reordered tick would show a wrong value. UDP multicast, common inside exchanges and co-located trading firms, is not usable over the public internet to phones. See TCP and UDP and real-time communication.
  • Internal fan-out. Inside the data centre the ticker's internal transport changed from a custom TCP protocol to ZeroMQ, then nanomsg-style messaging, and finally NATS, as the future-ready post describes. Each step was a response to measured limits.
  • Keep-alive and pooling. Lesson 5 showed how connection pools and keep-alive between HAProxy, Nginx and app servers cut handshake costs. See load balancing.
  • A latency baseline. Kite holds a 40 ms client round trip on a good connection as its baseline, and treats drift from it as an early warning to refactor. Setting an explicit latency budget like this, then watching it, is a habit every design needs (see observability).
  • HTTP versions on mobile. Lesson 19's flutter_curl work exists because HTTP/2 multiplexing and Brotli matter on high-latency mobile links (see HTTP and HTTPS).

Large blobs. Contract notes (Lessons 13 and 14) and Blobasaur (Lesson 12) are textbook large-object problems: keep blobs out of the main database, store them in object storage or a dedicated blob store, generate keys that spread load, and serve them by reference or presigned URL. See handling large blobs and object storage.

The interview delivery framework, applied to a broker. The handbook's interview framework walks requirements, estimates, API, data model, high-level design, deep dives and wrap-up. Zerodha's posts give realistic answers at every step:

StepZerodha-flavoured answer
Functional requirementsPlace, modify and cancel orders; live ticks; holdings and P&L; reports and contract notes
Non-functional requirementsOrder path latency in tens of ms; correctness over availability for money; deadline-bound batch; regulatory audit
EstimatesMillions of users, over 1 million concurrent at peak; 10 million plus orders a day in busy periods; tens of millions of tick packets a second fanned out
APIClean REST/JSON for orders and portfolio; WebSocket binary stream for ticks; OAuth-like flow for third parties (Lesson 20)
Data modelPostgres for transactional data, partitioned by financial year (Lesson 10); Redis for hot state; ClickHouse for logs and analytics
High-level designEdge proxies, Go services, risk proxy (Veto) before the OMS, ticker fan-out, Kafka for decoupling, report job servers
Deep divesPre-validation and rule engines; tick fan-out; report precomputation; 1.5 million contract notes by deadline
Wrap-upTrade-offs of self-hosting, vertical scaling and single-region deployment, and how each would change at 10x

The primer's scaling ladder, revisited. Lesson 8 compared Zerodha to the System Design Primer's "scale to millions of users on AWS" exercise, which grows a single box into a layered, cached, replicated, autoscaled system by repeatedly benchmarking, profiling and fixing the current bottleneck. Zerodha follows the same loop but answers each step with self-hosted, vertically scaled components where the primer reaches for a managed service. Both agree on the essential point: scaling is iterative, guided by measurement, and you should add only what the current bottleneck needs. See scaling from zero to millions.

When to Use It#

Study the Zerodha posts when:

  • You are on a small team running a large, regulated workload and want proof that a few senior engineers can operate it on self-hosted, boring technology.
  • You are deciding build versus buy versus self-host and want a worked example of the trade-offs and costs on both sides.
  • You face deadline-bound batch work, like statements, invoices or regulatory reports, that must finish in a fixed window.
  • You need to scale Postgres to very large tables without moving to a distributed database.
  • You are designing a trading, payments or other financial system where correctness, auditability and latency all matter.
  • You are preparing for interviews and want realistic numbers and trade-offs for a stock-broking or real-time pricing problem.

When NOT to Use It#

  • Spiky, global, elastic workloads. If traffic can grow 10 times in an hour from anywhere in the world, Zerodha's planned, vertically scaled, single-region approach is the wrong model. Look at the Netflix and Discord pages instead.
  • Teams without operations depth. Self-hosting without people who know the internals turns cost savings into outages.
  • When time to market dominates. A young product searching for fit should buy managed services and spend engineering time on the product.
  • Hyperscale distributed data. If one partitioning key cannot keep each table on one machine, you need partitioning and sharding across nodes or a distributed database, which Zerodha largely avoids.

How to Implement It#

To apply Zerodha's lessons to your own system:

  1. Write down assumptions. Traffic shape (fixed hours or 24x7, peaks and their size), latency budgets per path, the consistency each piece of data needs, and who will maintain each component.
  2. Measure before you design. Load-test the current system, profile it and find the actual bottleneck: often the database, connection handling or serialisation, rarely the language.
  3. Start boring and vertical. A single well-tuned Postgres, Redis and a Go or Java service on large machines go very far. Add replicas for reads and failover before you add shards.
  4. Precompute what is hot. Cache pre-serialised responses for the most-read endpoints, and run heavy reports as async jobs that write results to a cache (Lesson 11).
  5. Partition by a natural key. Time-bucket large ledgers by year or month, archive old partitions, and federate the rare cross-partition query.
  6. Guard expensive components. Put a cheap validating proxy in front of anything costly or licensed, so it only processes work likely to succeed.
  7. Decouple with a bus, not a web of APIs. Have sources of truth publish changes to Kafka topics, and let consumers subscribe (Lesson 3).
  8. Own observability cheaply. Ship logs to a columnar store like ClickHouse and metrics to Prometheus with a long-term store, with a strict label budget.
  9. Rehearse the deadline. For batch jobs with regulatory deadlines, run full-size dress rehearsals and keep the infrastructure ephemeral and scripted.
# Handbook's illustration: a Zerodha-style service budget and stack sheet
service: portfolio-api
traffic:
  hours: "09:00-16:00 IST weekdays, peak at open and close"
  peak_rps: 40000
  avg_rps: 6000
latency_budget_ms:
  p50: 10
  p99: 60
data:
  primary: postgres-16  # vertically scaled, 1 primary + 2 replicas
  partitioning: by_financial_year
  hot_cache: redis      # pre-serialised JSON, ETag support
  reports: dungbeetle   # async SQL jobs, results cached
connections:
  db_pool_per_instance: 20
  upstream_keepalive: true
observability:
  logs: vector -> clickhouse
  metrics: prometheus -> victoriametrics
  max_label_cardinality: 10000
ownership:
  principal_devs: 2
  on_call: weekly rotation

Technology choices.

NeedZerodha choiceAlternativesWhen each fits
Transactional databasePostgreSQL, vertically scaled, partitionedMySQL; CockroachDB or SpannerMySQL for similar scale with different tooling; distributed SQL when one node cannot hold a partition or you need multi-region writes
Hot cacheRedis with pre-serialised valuesMemcached; in-process cachesMemcached for simple key-value at huge scale; in-process for tiny, read-only data
Event busKafkaNATS, RabbitMQ, PulsarNATS for low-latency fan-out; RabbitMQ for task queues with routing; Pulsar for multi-tenant geo-replication
Real-time fan-outGo ticker over WebSockets, NATS internallySSE, managed pub/subSSE for one-way browser streams; managed pub/sub when you lack ops capacity
LogsVector plus ClickHouseELK, Loki, managed SaaSELK for full-text-heavy search; Loki for cheap label-indexed logs; SaaS when ops time is scarce
MetricsPrometheus plus VictoriaMetricsThanos, Mimir, managedThanos or Mimir for multi-cluster global view; managed for small teams
Batch orchestrationNomad, ephemeral cluster, TasqueueKubernetes Jobs, AWS Batch, TemporalKubernetes if you already run it; Batch for fully managed; Temporal for long, stateful workflows
Mobile clientFlutterNative, React Native, Kotlin MultiplatformNative for platform-heavy apps; React Native for web-heavy teams; KMP to share logic but keep native UI
Risk rulesGo plugins via VetoOPA/Rego, embedded scripting, expression enginesOPA for policy across many services; scripting for user-authored logic needing sandboxing

Trade-offs#

Choice Zerodha madeWhat it boughtWhat it cost
Self-host nearly everythingVery low IT cost, control, compliance, no lock-inOps load on a small team; no managed conveniences
Vertical scaling and single primariesSimplicity, strong consistency, fewer moving partsHard ceilings; bigger blast radius per node
Postgres for hundreds of billions of rowsOne familiar engine, SQL everywhereCareful partitioning, vacuum and index work forever
Precomputed reports and hot cachesFast reads under peak loadStaleness windows and cache management
Go plugins for rulesNative speed, full language, self-testsBrittle toolchain, no sandbox, no unloading
Early bet on FlutterOne codebase for two developersOwning engine-level quirks and plugin forks
Kite Connect as public APIA platform business and ecosystemAPI freeze and partner risk
No marketing or engagement trackingFewer systems, user trust, privacySlower growth, less product telemetry
Hybrid office for core teamFast decisions, wellbeingLess flexibility, commuting, narrower hiring pool

Common Pitfalls#

  • Copying the stack without the conditions. Zerodha's choices rest on fixed market hours, a senior stable team and profitability. Without them, self-hosting can be the expensive option.
  • Treating vertical scaling as infinite. Know your ceiling and the date you will hit it. Plan partitioning before the largest machine is not enough.
  • Building a DSL for business users. Lesson 18 shows how expression languages grow into unmaintainable half-languages. Prefer a real language with templates and tests.
  • Benchmarking the wrong thing. Lesson 14's storage benchmark and Lesson 12's Blobasaur tables were tied to real workloads. Synthetic averages hide tail latency and key-distribution effects like the KSUID prefix trap.
  • Ignoring metrics cardinality. One high-cardinality label can multiply series by a million and bring down a metrics store.
  • Assuming async communication suits every organisation. Lesson 23 shows sync-heavy businesses pay a real price.

Real-World Examples#

  • Stripe shares the "boring tech, deep correctness" attitude in payments; compare idempotency and API design in the Stripe page.
  • Discord went the other way on data, moving to Cassandra and then ScyllaDB for trillions of messages; see the Discord page for when a distributed store is the right call.
  • Uber shows what a very large organisation does with thousands of microservices and custom platforms; see the Uber page for the opposite end of the team-size spectrum.
  • Meta runs massive caches and graph stores; the Meta page shows caching at a scale where single nodes are irrelevant.
  • Netflix relies on AWS and chaos engineering for elastic global streaming; the Netflix page is the counterpoint to Zerodha's self-hosting.
  • Stock exchanges and brokers in general: see the stock exchange case study for matching engines and order flow.

In the Interview#

Deep Dive: designing a small brokerage app with Zerodha's lessonsShow

Problem. A new broker expects 200,000 users, 20,000 concurrent at market open, 300,000 orders a day and live ticks for 2,000 instruments.

Estimates. Peak order rate at open: if 15 percent of daily orders arrive in the first 15 minutes, that is 45,000 orders in 900 seconds, 50 per second, with bursts to perhaps 500 per second. Tick fan-out: 20,000 clients watching 30 instruments each, with each instrument ticking twice a second, is 1.2 million tick messages per second to clients before coalescing, which a few Go fan-out servers can handle using binary frames and per-client batching.

Design.

  • Edge. Two HAProxy nodes with keep-alive pools to app servers, TLS terminated at the edge.
  • Order path. A stateless Veto-style risk proxy with compiled rules in front of a vendor OMS. Kill Switch and nudge rules live in the same proxy.
  • Ticks. Exchange feed into a ticker service, NATS for internal fan-out, WebSocket servers pushing binary frames.
  • Data. One Postgres primary with two replicas on large machines, ledger partitioned by financial year; Redis for sessions, hot positions and pre-serialised holdings.
  • Reports. A dungbeetle-style job server runs heavy SQL on a replica and caches results.
  • Statements. End-of-day contract notes generated by a burst cluster with a task queue, stored in object storage, emailed by a self-hosted mail pipeline.
  • Observability. Logs to ClickHouse, metrics to Prometheus with a strict label budget.

What you give up. Multi-region failover (one region with a warm standby is enough for an India-only, fixed-hours business), elastic burst capacity, and managed conveniences. What you gain. A system four or five engineers can understand completely.

When to change course. If orders grow 50 times or the broker expands to markets in other time zones, revisit single-region, vertical scaling and the vendor OMS.

Key Takeaways#

  • Zerodha runs India's largest retail stockbroker with a tech team of about 30, using self-hosted, boring technology: Go, Postgres, Redis, Kafka and ClickHouse.
  • Scaling with common sense means measuring the bottleneck, tuning pools, caches and serialisation, and scaling vertically before distributing.
  • Postgres can hold hundreds of billions of rows when the data is partitioned by a natural business key and heavy reads are precomputed.
  • Deadline-bound batch work, like 1.5 million contract notes, is solved with ephemeral clusters, careful storage benchmarks and good key design.
  • Cheap observability is possible with ClickHouse for logs and Prometheus with VictoriaMetrics for metrics, if label cardinality is controlled.
  • Clever DSLs for business rules tend to become usability bottlenecks; a real language with built-in tests serves operators better.
  • Framework choice for real-time mobile UI is decided by the hardest screen on the weakest device.
  • A clean wrapper API over a vendor became Kite Connect, a profitable platform, showing that stable interfaces are a long-term asset.
  • Product restraint (no ads, no engagement tracking, nudges and kill switches) removes whole systems from the architecture.
  • The approach depends on fixed market hours, a senior and stable team and profitability; without those, managed services are often the better trade.