Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

Product wants an export of any filtered list in the admin UI, which today can request 50 million rows. Design how the backend runs these queries without hurting OLTP traffic.

I would run exports as asynchronous jobs instead of inside HTTP requests, read the rows on a read replica or a snapshot through a separate connection pool with its own statement timeout, and stream them with a database cursor rather than loading lists into memory. The job walks the table in keyset order by primary key so it can resume after a failure, writes the file to object storage and hands the user a signed, expiring link. Exports are limited and audited because they move personal data, and the very largest ones belong in a warehouse or data lake, not on the OLTP database.

Why this question is asked

An export button looks like a small feature: take the current filter, turn it into CSV, download. With 50 million rows it becomes one of the most dangerous features in the product, because a naive implementation holds a connection for an hour, fills the JVM heap, times out at the load balancer and slows down every customer while it runs. Interviewers ask this design question to see whether we can protect online transaction processing (OLTP), the many short reads and writes that serve live users, from a heavy analytical workload that shares the same data. In this answer, we will look at why the naive approach fails, then design the job flow, the data source, the streaming read, resumability, the security side, and when to move exports off the OLTP database entirely.

1Why the Naive Export Fails

The naive version is a controller method that runs the filtered query, collects the results into a List, writes CSV into the response and returns. Each part breaks at this size. At roughly 200 bytes per row, 50 million rows are about 10 GB of data, far more than the heap. Even if we stream the response, an HTTP request that runs for 40 minutes will be cut off by a proxy or a browser, and the user has no way to resume. Meanwhile the query holds a connection from the same pool as checkout, and its scan competes for disk and buffer cache with live traffic.

There is also a quieter problem: a single transaction kept open for an hour on the primary holds back vacuum in PostgreSQL, so dead rows across the database cannot be cleaned up until it finishes. So the design has to move the work out of the request, off the primary, and into small, restartable steps.

2Running Exports as Jobs

The request only creates a job. The API stores the filter, the requesting user and a status of QUEUED, and returns 202 Accepted with the job id. A worker pool, separate from the web threads, picks jobs from a queue and processes them; the UI polls the job or receives a notification when it finishes. Limiting concurrency is easy here: if the worker pool has 3 slots, at most 3 exports run at once, whatever the users click.

Step throughExport as an asynchronous job
Admin UIExport APIWorkerRead replicaObject storage
POST /exports {filter}
202 Accepted, jobId
claim next QUEUED job
stream rows in keyset chunks
rows via cursor
upload file parts
mark DONE, save object key
GET /exports/{jobId}
signed link, expires in 1 hour

9 messages in order. Play them, or step through them one at a time.

3Choosing Where the Query Runs

The export should read from a read replica, a copy of the database that receives changes from the primary and serves only reads, so the heavy scan never touches the server that takes writes. The export workers get their own connection pool, for example a separate HikariCP pool with 3 connections, so they cannot exhaust the connections the web tier needs. That pool's connections set a statement timeout suitable for long reads, and the database role used by the exporter can have its own limits.

A replica has one catch in PostgreSQL: a long query on a hot standby can be cancelled when the primary's changes conflict with the rows it is reading, unless hot_standby_feedback is on, which in turn can bloat the primary. Breaking the export into shorter keyset chunks, as we do next, keeps each query short and avoids most of these conflicts. Some teams instead export from a restored snapshot or a dedicated reporting replica, which gives a consistent point in time with no impact at all on production.

4Streaming Rows With a Cursor

Inside the worker we never build a List of rows. With the PostgreSQL JDBC driver, a query only streams if autocommit is off and a fetch size is set; otherwise the driver reads the whole result into memory before returning the first row. With a fetch size of 5,000, the driver uses a cursor and keeps only 5,000 rows in memory at a time.

Java
@Transactional(readOnly = true) // autocommit off for this connection
public void exportChunk(ExportJob job, long afterId, CsvWriter out) {
jdbcTemplate.setFetchSize(5_000); // stream in batches of 5,000 rows (better: a dedicated JdbcTemplate)
jdbcTemplate.query(
"SELECT id, customer_id, status, total, created_at FROM orders " +
"WHERE " + job.whereSql() + " AND id > ? ORDER BY id LIMIT 1000000",
ps -> { job.bind(ps); ps.setLong(job.paramCount() + 1, afterId); },
rs -> { out.write(rs); }); // one row at a time, written straight to the file part
}
// memory stays flat at roughly 5,000 rows, whatever the total size

Notice that the filter is built with bind parameters from the stored job definition, exactly like the interactive search, so an export cannot inject SQL. The callback writes each row straight to the output, so the heap only ever holds one batch. In MySQL Connector/J, the equivalent is a forward-only, read-only statement with fetch size Integer.MIN_VALUE, or useCursorFetch=true with a positive fetch size; check your driver version.

5Making the Job Resumable With Keyset Iteration

A 50 million row export will sometimes fail half way: a replica restarts, a deploy kills the worker, a network blip. If the job can only start again from zero, a big export may never finish. So the job walks the table in primary key order in chunks, for example one million rows per chunk with WHERE id > :lastId ORDER BY id. After each chunk is written as a part of the file in object storage, the job records the last id it wrote. On a restart it continues from that id.

Step throughOne export job, chunk by chunk
  1. Load job and lastIdlastId = 0 for a new job
  2. Query chunk: id > lastId ORDER BY idLIMIT 1,000,000, streamed
  3. Write part file to object storagefor example part-0007.csv.gz
  4. Save lastId and part numbera checkpoint in the job table
  5. More rows left?
    YesNext chunkNoComplete the upload and mark DONE

5 steps in order. Play them, or step through them one at a time.

Keyset iteration by id is also efficient: each chunk starts with an index seek on the primary key, so chunk 40 costs the same as chunk 1, unlike OFFSET. The trade-off is that chunks are read at slightly different moments, so the export is not a single consistent snapshot. For most admin exports that is acceptable; when it is not, we export from a snapshot or use a single repeatable read transaction on a dedicated replica.

6Security, Limits and Audit

An export of 50 million customer orders is a data breach waiting to happen if anyone can trigger it. So exports need permissions of their own, separate from viewing the list. Each job is recorded with who requested it, the filter, the row count and when the file was downloaded. Columns with personal data can be masked unless the user has a stronger role. Files go to object storage, encrypted, with a lifecycle rule that deletes them after, say, 7 days, and the user downloads them through a signed URL that expires after an hour, instead of the file passing through our application servers.

I would also cap exports per user per day and above some size, say 5 million rows, require an approval or route the request to the data platform.

7When the OLTP Database Is the Wrong Place

If exports of tens of millions of rows are frequent, the question changes. A data warehouse or lakehouse, fed from the OLTP database with change data capture, stores data in columnar files designed for exactly this kind of scan, and can write the result directly to object storage. Then the admin export becomes a query against the warehouse, and the OLTP database only serves live traffic. I would start with the job design above, measure how often big exports run and how long they take, and move the largest ones to the warehouse when the numbers justify it.

8Follow-up questions

Why is a fetch size alone not enough with the PostgreSQL driver?

Because the driver can only use a server-side cursor inside a transaction. With autocommit on, each statement is its own transaction, so the driver fetches the entire result at once and ignores the fetch size. Turning autocommit off, which a read-only @Transactional method does, and using a forward-only result set makes it stream in batches.

9Conclusion

In this answer, we designed exports as asynchronous jobs that read from a replica or snapshot through their own pool and timeout, stream rows with a cursor so memory stays flat, iterate in keyset order by primary key so they can resume, and write to object storage behind a signed link. We also saw why exports need permissions, limits and audit, and when the largest exports belong in a warehouse instead of the OLTP database.

What to say in the interviewAbout 80 seconds aloud

Open with

I would never run a 50 million row export inside an HTTP request. The request creates an export job and returns 202 with a job id; a small worker pool processes jobs, so concurrency is capped.

Then, if they want more

The workers read from a read replica or a snapshot through their own connection pool with its own timeout, so they cannot take connections or I/O from checkout. Rows are streamed with a cursor: in PostgreSQL JDBC that means autocommit off and a fetch size, otherwise the driver loads everything into memory.

The job walks the table in keyset order by primary key in chunks of, say, a million rows, writes each chunk as a compressed part file in object storage and checkpoints the last id, so it can resume after a failure. Keyset chunks also keep each query short, which avoids long transactions holding back vacuum and replica conflicts.

The user gets a signed, expiring link. Because exports move personal data, I would require a separate permission, audit who exported what, mask sensitive columns and cap sizes. If very large exports are common, I would move them to a warehouse fed by CDC.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Product wants an export of any filtered list in the admin UI, which today can request 50...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/fd7e884f23/