Video in progress

Users ask to download a report with millions of rows as CSV or Excel. How do you design this feature so it doesn't take the service down?

I don't generate the report synchronously inside the HTTP request: an asynchronous job, reading from the DB as a stream with a cursor, writing the file to storage in chunks, and a download link when it is ready. For Excel you use a streaming writer (Apache POI SXSSF) and limit the number of concurrent exports.

📖 Answer

How the synchronous version fails: the request takes 3 minutes, the proxy cuts the connection at 60 seconds, the user presses "retry", and now there are two heavy requests. findAll() pulls a million objects into the heap. A plain XSSFWorkbook holds every cell in memory and asks for gigabytes of heap at a million rows.

The design:

  1. The job. POST /exports → 202 Accepted + a job ID. The job goes into a queue, its state is in the database (QUEUED/RUNNING/DONE/FAILED), with a progress percentage.
  2. Reading. Stream with a JDBC cursor: on PostgreSQL fetchSize only works when autocommit=false. In Spring Data, a query returning Stream<T> + @Transactional(readOnly = true); in Hibernate, a projection or StatelessSession so the objects don't pile up in the persistence context. It is better for the long transaction to run on a replica: on the main database it interferes with vacuum.
  3. Writing. CSV: a BufferedWriter straight into a GZIPOutputStream and from there into the storage's multipart upload. Excel: SXSSFWorkbook(100): only the last 100 rows stay in memory, the rest goes to a temporary file; at the end, close() and, depending on the POI version, dispose() delete the temporary files, otherwise the temp directory keeps filling up. An Excel sheet is limited to 1,048,576 rows: for more, use several sheets or CSV.
  4. Limits. A maximum of N exports at a time (across the whole cluster, not per pod), one active export per user, a maximum row count. Without these, a single user loads the whole DB.
  5. Delivery. The finished file is a presigned URL valid for 24 hours, deleted by a lifecycle rule. A notification or email to the user.

One more risk: CSV injection. If a value starts with =, +, - or @, Excel executes it as a formula. User-entered text in an export has to be escaped by prefixing it with ': this comes up a lot in pentest reports.