Returning one million records in a single API response is usually the real problem. The first question is: who consumes the data and why? The right design depends on the use case. 1. Do not send a million rows to a UI Users cannot read a million rows. Use: - Pagination with keyset (cursor) pagination: WHERE Id > @lastId ORDER BY Id FETCH NEXT 100 ROWS ONLY. It stays fast on deep pages, unlike OFFSET. - Server-side filtering, sorting and search so users find what they need. - Aggregations or summaries computed in the database (or precomputed) instead of raw rows. 2. If a client genuinely needs all the data (export, integration, data sync) - Make it asynchronous: the API accepts the export request (202 Accepted), a background worker generates a file (CSV, Parquet or compressed JSON) and uploads it to blob storage, and the client downloads it from a time-limited URL. No HTTP request stays open for minutes. - Or stream the response instead of buffering: in ASP.NET Core return IAsyncEnumerable<T> with System.Text.Json streaming (or write CSV directly to the response body), using AsNoTracking and AsAsyncEnumerable() in EF Core so rows flow from the database to the client without loading everything into memory. - For system-to-system sync, offer incremental queries (changes since a timestamp or change token) instead of full dumps every time. 3. Optimise the query - Select only needed columns (projection), not SELECT * with large text columns. - Indexes that support the filter and sort (covering indexes avoid lookups). - AsNoTracking for read-only EF Core queries, or Dapper or raw ADO.NET for very large reads. - Read from a replica so the export does not slow transactional traffic. - Avoid N+1 queries and huge joins; split into batches if needed. 4. Reduce transfer cost - Response compression (Brotli or gzip) and compact formats; avoid deeply nested JSON. - HTTP/2 and keeping the API close to the database. 5. Protect the system - Limits on page size and export frequency, rate limiting, timeouts and cancellation tokens. - Caching results when the same large dataset is requested repeatedly. Sample answer: "I would first avoid returning a million rows synchronously: paginate with keyset pagination for UI use cases, and for exports use an asynchronous job that streams rows from the database with AsNoTracking into a compressed file in blob storage, then notifies the user with a download link."
Ravindra Wadile · · 0 likes