# How Zerodha Generates 1.5 Million PDFs in 25 Minutes
*Zerodha cut its daily contract note job from 8 hours to 25 minutes by rebuilding it as a short-lived fleet of Go workers, with Typst, S3, and Nomad.*
By [Rohit Lakhotia](https://scaleengineer.com/authors/rohit-lakhotia)
Published: 2026-11-30
Canonical: https://scaleengineer.com/blog/how-zerodha-generates-1-5-million-pdfs-in-25-minutes
---
Every evening, after the stock market closes, millions of Indians check their email for one boring\-looking document: the contract note\. If you trade stocks in India, your broker must send you this digitally signed PDF for every day you trade\. It lists each trade you made and every charge you paid\. Its layout, contents, and delivery time are all set by regulators, and it must reach you before the next trading day begins\.

Now imagine being Zerodha, one of India's largest brokers\. On an average day, more than 1\.5 million users trade, and on a volatile day that number can double\. That means generating, signing, and emailing 1\.5 million\+ PDFs every single night\.

Zerodha's old system took 7 to 8 hours to do this, and even longer on busy days\. So the team threw it away and rebuilt it from scratch\. The new system does the same job in about 25 minutes, at negligible cost\. Let's understand how Zerodha achieved it in this blog today\.

## Why This is Harder Than it Sounds

Zerodha can't start generating contract notes the moment the market closes\. First, stock exchanges and other market institutions send their end\-of\-day data files, and Zerodha's back office has to do all the number\-crunching and tallying\. These files themselves often arrive late\.

So by the time the data is ready, the window to generate and send millions of PDFs is already tight, and it can't move, because regulations require delivery before the next trading day\.

## The Old System

The old pipeline had four steps:

1. A Python app read the end\-of\-day CSV files and filled in an HTML template using Jinja\.
2. Chrome, controlled through a tool called Puppeteer, converted each HTML page into a PDF\.
3. A Java command\-line tool digitally signed each PDF\.
4. Self\-hosted Postal email servers sent the signed PDFs\.

All of this ran on one big server that was started just for the job\. In simple terms: one very large machine did all the work\.\. This approach is called vertical scaling: when you need more power, you get a bigger machine\. But a single machine can only get so big\. As trading volume grew, the job grew to 7 to 8 hours\. The Postal email server also became a serious bottleneck\.

## The New Idea: Many Machines, Briefly

Zerodha decided the only way forward was horizontal scaling: instead of one bigger machine, use many machines working in parallel and add more whenever needed\. But which kind of "many machines"?

**Why Not Serverless?**

One option was FaaS \(Functions as a Service\), like AWS Lambda, where small functions run on demand\. Zerodha ruled it out for three reasons:

- Cold starts: functions can take time to spin up\.
- Communication overhead: lots of small functions passing data around adds delay\.
- Cost per run: paying per invocation adds up across millions of jobs\.

**Large Machines That Live for Minutes**

Instead, Zerodha went back to first principles\. Generating PDFs is CPU\-bound work, so the fastest and cheapest approach is to:

1. Start a few large servers\.
2. Keep every CPU core 100% busy, with almost no idle time\.
3. Destroy the servers the moment the work is done\.

These short\-lived servers are called ephemeral instances\. You pay only for the minutes they run, and nothing sits idle\.

**Why No Fine\-Grained Planning?**

Workloads vary wildly\. One user's contract note might be 2 pages, while another active trader's might be 2,000 pages\. Planning exactly how much CPU each job needs is impossible\.

So Zerodha does something simpler: throw all the jobs into a shared pool of workers and let them chew through it\. Yes, one 2,000\-page PDF might hold a CPU core 100 times longer than a normal one\. But with a huge number of cores working at once, it evens out\.

## The Architecture: An Assembly Line

![](https://media.beehiiv.com/cdn-cgi/image/fit=scale-down,format=auto,onerror=redirect,quality=80/uploads/asset/file/f7dd52c1-dfe7-4a80-b783-5a1adb9d604c/image.png?t=1795366578)

Source: [Zerodha](https://zerodha.tech/blog/1-5-million-pdfs-in-25-minutes/)

Think of the new system as a factory assembly line\. Each user's contract note passes through four stations:

1. Process data: read the CSV files and prepare the content\.
2. Generate PDF: turn that content into a PDF\.
3. Sign PDF: add the digital signature\.
4. Email PDF: send it to the user\.

Each station has its own group of workers\. A worker picks up a job, does its part, saves the result, and passes the job to the next station\.

**Rewriting in Go**

Zerodha rewrote the old Python worker from scratch in Go, a language that's very good at running many tasks at the same time\. That alone made workers dramatically faster and lighter on resources\.

**Tasqueue: Passing Jobs Along**

To pass jobs between workers, Zerodha evaluated existing tools and ended up building its own lightweight Go library called Tasqueue\. It lets you define a chain of jobs, so one finishing automatically triggers the next:

```
// Pseudocode
chain = []tasqueue.Job{
    tasqueue.NewJob("generate_pdf", payload),
    tasqueue.NewJob("sign_pdf", payload),
    tasqueue.NewJob("email", payload),
}
tasqueue.NewChain(chain, tasqueue.ChainOpts{})
```

**S3 as the Conveyor Belt**

Workers don't send files directly to each other\. Instead, each worker:

1. Downloads its input file from S3 \(Amazon's storage service\)\.
2. Does its work\.
3. Uploads the result back to S3 for the next worker\.

**Redis as the Control Room**

Redis, a fast in\-memory data store, plays two roles:

- Job broker: it hands out jobs to the workers\.
- Status board: it tracks the state of every job\.

By checking Redis, the team can see how many jobs are done and which ones failed\. Failed jobs can then be retried for just those specific users\.

## Generating PDFs: From Chrome to LaTeX to Typst

PDF generation is the heaviest step, and Zerodha went through three tools to get it right\.

### Step 1: Chrome \(Too Slow\)

Turning HTML into PDF with Puppeteer meant launching a hidden \("headless"\) copy of Chrome for the job\. That's like starting a full web browser just to print a document\. As volume grew, it became slow and resource\-hungry\.

### Step 2: LaTeX \(Faster, But Problems\)

After benchmarking several options, Zerodha switched to LaTeX, a typesetting system widely used for academic papers and books\. They converted their HTML templates to LaTeX and used a tool called `pdflatex` to make the PDFs\.

The result was 10X faster than Chrome, using far fewer resources\. They ran it in production for a couple of months, but three problems showed up:

- Memory limits: very large reports, up to thousands of pages, used lots of memory, and `pdflatex` can't allocate memory dynamically\. Tweaking its settings didn't fix it\.
- Confusing crashes: switching to `lualatex`, which can allocate memory dynamically, mostly solved the memory issue\. But on huge tables it sometimes crashed with error messages that were nearly impossible to debug\.
- Huge Docker images: LaTeX needs many libraries and packages, so the Docker images were very large\. Even with caching, servers took longer to start before workers could run\.

### Step 3: Typst \(The Breakthrough\)

Then Zerodha found Typst, a modern typesetting system written in Rust that ships as a single small program\.

- Easier to use: simpler, consistent styling without piles of third\-party packages\.
- Clearer errors: much easier to debug problems caused by bad input data\.
- Faster: 2 to 3 times faster than LaTeX for small files\. For huge documents, the gap is dramatic: a 2,000\-page contract note takes about 1 minute with Typst versus 18 minutes with lualatex\.
- Smaller images: a single small binary means much smaller Docker images and faster server startup\.

## Digitally Signing PDFs

Regulations require contract notes to be digitally signed and encrypted\. PDF signatures are complex, and Zerodha couldn't find any fast, free, open\-source library that could sign PDFs in bulk\.

So they built a small workaround\. They wrapped the Java library OpenPDF in a tiny HTTP server\. The Java runtime starts once and then handles many signing requests at the same time, instead of starting fresh for every PDF\.

This server runs as a sidecar, a helper process that sits right next to each signing worker on the same machine\.

## Storing 7 Million Temporary Files

Each PDF is usually 100 to 200 KB, though some run into megabytes\. Counting every intermediate file \(Typst templates, unsigned PDFs, signed PDFs, and so on\), an average day produces about 7 million temporary files\.

Since workers on many different machines need each other's output, they need shared storage that every machine can read and write\.

### Option 1: EFS \(Too Slow for Small Files\)

Zerodha first tested AWS EFS \(Elastic File System\), a shared network drive\. With 512 Mb/s of provisioned throughput, they benchmarked reading and writing 10,000 files of 100 to 200 KB each at the same time:

- General Purpose mode: hit EFS's limit on file operations per second and took 4 to 5 seconds\.
- Max I/O mode: even worse, at 17 to 18 seconds, because of higher latency\.

For comparison, the same test on EBS, a disk attached to a single machine, took about 400 milliseconds\. But a disk attached to one machine can't be shared across a whole fleet\.

EFS clearly wasn't built for millions of tiny files\.

### Option 2: S3 \(Chosen\)

S3 took about 4 to 5 seconds for a similar number of files, about the same as EFS General Purpose\. But S3 was far cheaper and much simpler to manage, so Zerodha chose S3\.

AWS also suggested FSx for Lustre, a high\-performance file system often used in supercomputing\. But it was complicated to set up and wasn't available in the Mumbai region \(ap\-south\-1\), where Zerodha's operations must run\.

## The S3 Rate Limit Puzzle

Switching to S3 created a new problem\.

**S3 Limits Requests Per Prefix**

In S3, a prefix is the beginning part of a file's path, like a folder name\. S3 limits how many requests you can make per prefix:

- Writes and deletes \(PUT/COPY/POST/DELETE\): up to 3,500 requests per second per prefix\.
- Reads \(GET/HEAD\): up to 5,500 requests per second per prefix\.

Go over that, and S3 replies with "503 Slow Down" errors\.

Zerodha's workload is very bursty\. In one trial run, they made about 1\.61 million requests in 5 minutes, averaging about 5,300 per second, with an error rate of about 0\.13%\. They hit rate limits frequently, even when retrying each request up to 10 times\.

**The First Attempt: Unique IDs**

AWS documentation says to spread load across many unique prefixes\. So Zerodha gave each contract note a unique ID called a ksuid and used it as the folder name:

```
bucket/2CTgQKodxGCCXxXQ2XlNyrVSFIV
bucket/2CTgQKtyZ2O9NGvt1gSo75h5N9V/
bucket/2CTgQKwBQasuWHaz1QnOIWDNrtc/
bucket/2CTgQL3U7griLK2tyHDOLiYe7w4/
```

But they still got rate limited\. Why?

**What Was Really Happening**

Zerodha asked AWS support, and the answer was surprising\.

ksuids are time\-sortable, so IDs created around the same time start with the same characters\. Notice how every ID above begins with `2CTgQ`\. To S3, all these "unique" folders looked like they shared one prefix, so almost all requests hit the same partition\.

Here's how S3 actually scales:

- S3 splits busy prefixes into more partitions over time\. Each new partition adds another 3,500 writes and 5,500 reads per second\.
- But if you start sending traffic to a completely new prefix, S3 has to start splitting all over again, and the old, already\-split partitions go cold\.
- Cold partitions lose their benefit, so the scaling process restarts the next time traffic spikes\.

In simple terms: S3 rewards you for reusing the same few prefixes every day, not for constantly inventing new ones\.

**The Fix: 10 Fixed Prefixes**

Zerodha switched to a simple, fixed folder pattern, starting each path with a number from 0 to 9:

```
bucket/1-contract-notes-data/
bucket/1-tmp-pdf/
bucket/1-signed-pdf/
...
bucket/9-contract-notes-data/
bucket/9-tmp-pdf/
bucket/9-signed-pdf/
```

Requests now spread evenly across 10 fixed prefixes, which multiplies the rate limit by ten\. And because the prefixes never change, S3's partitions stay useful day after day\.

Zerodha also asked AWS to pre\-warm these partitions so they're ready for heavy traffic from the very first second of the nightly burst\.

## Orchestrating Everything With Nomad

Someone has to start the servers, put the right workers on the right machines, and shut everything down afterwards\. That's called orchestration\.

Zerodha uses Nomad, a tool from HashiCorp that schedules programs across many machines\. All Zerodha deployments already use Nomad, and the team finds it far easier to run than Kubernetes\.

The setup uses three tools:

- Terraform: creates and destroys infrastructure from code\.
- Nomad: decides which worker runs on which machine\.
- Rundeck: a small control server with a dashboard that runs the whole workflow\.

**A Brand\-New Cluster Every Night**

Every midnight, Zerodha uses its own Terraform module to create a fresh Nomad cluster just for this job\. The module sets up everything needed: launch templates, Auto Scaling Groups \(ASGs\), IAM roles, and security groups\.

There are separate ASGs \(groups of identical servers\) for different jobs, like generating PDFs, signing PDFs, and sending emails\. PDF generation needs much more computing power than signing, so each group can be scaled independently\.

### Phase 1: Initialization

Rundeck runs Terraform to launch the Nomad servers and the worker machines\. It then checks that every machine is ready to accept jobs before moving on\.

### Phase 2: Job Deployment

Nomad deploys the Go worker programs, mostly pulled from S3, onto the machines, where they start listening for jobs\.

Zerodha uses two Nomad features here:

- System jobs: guarantee exactly one copy of a worker runs on every matching machine\. They're similar to DaemonSets in Kubernetes\.
- Constraints: every machine is tagged with its role \(for example, `worker-pdf` or `worker-signer`\), and constraints make sure PDF workers land only on PDF machines and signer workers only on signer machines\.

```
group "pdf-creator" {
  constraint {
    attribute = "${meta.ec2_nomad_client}"
    value     = "worker-pdf"
  }
}
```

While jobs run, Rundeck reads progress from Redis and shows it on its dashboard, in case an admin wants to check in\.

For this job, Zerodha currently runs about 40 instances, a mix of `c6a.8xlarge`, `c6a.4xlarge`, and `c6a.2xlarge` machines\.

### Phase 3: Teardown

A small program watches the count of successful jobs in Redis\. When everything is done, it runs Terraform to tear the cluster down: setting the server groups to zero, draining machines, stopping Nomad jobs, and shutting down the Nomad servers\.

From start to finish, the whole operation takes 25 minutes, and the cost is negligible\.

## Emailing 1\.5 Million PDFs

As soon as a PDF is signed, it's queued for the email workers\.

The old Postal email server was resource\-hungry and couldn't scale horizontally, which made it a bottleneck that couldn't be fixed\. Zerodha replaced it with Haraka, an email server that's easy to scale horizontally\. It runs as a self\-hosted, auto\-scaling cluster\.

Email workers keep many open connections to Haraka at once, using a library Zerodha wrote called smtppool, so emails go out at very high speed\.

One important detail: when you run your own email servers, your IP reputation decides whether your emails land in inboxes or spam folders\. Zerodha has built that reputation over almost a decade, mainly by never sending marketing emails, and definitely not spam\.

## The Results

- Time: from 7 to 8 hours down to about 25 minutes\.
- Scale: 1\.5\+ million PDFs processed, generated, signed, and emailed\.
- PDF speed: a 2,000\-page report now takes 1 minute instead of 18 minutes\.
- Cost: negligible, because servers exist only for the duration of the job\.
- Open source: the project led to several open\-source tools, including the Tasqueue job library\.

## The Bigger Picture

This isn't one giant software system\. As Zerodha puts it, it's more of a collection of small scripts and programs that work together, and any piece \(Rundeck, Nomad, S3\) could be swapped out if needed\.

The big idea is simple: start a few large machines, keep every CPU core fully busy, and shut everything down as soon as the work is done\. Nothing sits idle, so very little money is wasted\.

The rest of the gains came from questioning each step: replacing a web browser with a purpose\-built typesetting tool, picking storage that suits millions of tiny files, understanding how S3 actually scales, and swapping a bottlenecked email server for one that scales out\.

Zerodha now plans to move other heavy batch jobs onto the same framework and add real\-time metrics so it can adjust resources while jobs are running\.

## Key Takeaways

- The task: generate, sign, and email 1\.5\+ million regulated contract note PDFs every night before the next trading day\.
- The old way: one big server doing everything took 7 to 8 hours\.
- The new approach: many short\-lived servers kept fully busy, then destroyed\.
- Assembly line: four worker stages \(process, generate, sign, email\) connected by Tasqueue, with S3 for files and Redis for job state\.
- PDF generation: Chrome, then LaTeX \(10X faster\), then Typst, which renders 2,000 pages in 1 minute versus 18\.
- Signing: a Java OpenPDF HTTP server runs as a sidecar and handles many signing requests at once\.
- Storage: S3 beat EFS for millions of small files on cost and simplicity\.
- S3 rate limits: time\-sortable IDs all landed on one partition, so 10 fixed, pre\-warmed prefixes fixed it\.
- Orchestration: a fresh Nomad cluster every night, created by Terraform, run by Rundeck, and torn down when finished\.
- Email: Haraka replaced Postal, scaling horizontally with pooled connections\.
- Result: 25 minutes end to end at negligible cost\.

Official blog from Zerodha: [1\.5\+ million PDFs in 25 minutes](https://zerodha.tech/blog/1-5-million-pdfs-in-25-minutes/)

By now, you must have had a clear idea of,** How Zerodha Generates 1\.5 Million PDFs in 25 Minutes? **In a nutshell, Zerodha replaced one big server with a short\-lived fleet of Go workers, switched to Typst for PDFs, fixed S3 rate limits with fixed prefixes, and used Nomad to spin everything up and down each night, cutting 8 hours to 25 minutes\.

**Congratulations\! You've just advanced another step in your tech journey\. Keep progressing\!**
