How do Bulk API pagination and chunking strategies prevent memory heap exhaustion during large extractions?
Answer
Basics: Heap limits (6 MB sync, 12 MB async) apply to Apex, not to Bulk API clients. The memory problem in large extracts is on the client or middleware side if it tries to load all rows at once, and the server-side problem is query timeouts on huge tables. Bulk API solves both with asynchronous query jobs and paged or chunked results.
How it works:
- Bulk API 2.0 query: POST a query job, poll until JobComplete.
- GET /jobs/query/{id}/results; results come as CSV pages. Use the maxRecords parameter and the Sforce-Locator response header to request the next page until the locator is null.
- Bulk API 1.0 uses batches and supports PK chunking: header Sforce-Enable-PKChunking: chunkSize=100000 (default 100,000, maximum 250,000) splits the query into Id ranges processed as separate batches.
- The client writes each page to disk or a stream and processes it.
Advanced / deep dive: PK chunking queries by indexed primary key ranges, which avoids full-scan timeouts on very large tables; Bulk API 2.0 handles chunking automatically, so there is no PK chunking header. Bulk query jobs do not support every SOQL feature (for example GROUP BY, OFFSET and TYPEOF; verify the current list), and relationship queries are limited. Results are retained for a limited time (about 7 days; verify) and daily limits apply to batches/records, so extract incrementally using SystemModstamp or LastModifiedDate watermarks. Alternative: Platform events/CDC for continuous change feeds, or Data Cloud/replication tools for analytics. Large result sets should be compressed if supported, and parallel downloads of chunks need care for rate limits.
Code / config example:
POST /services/data/vXX.0/jobs/query
{
"operation": "query",
"query": "SELECT Id, Name, SystemModstamp FROM Account WHERE SystemModstamp > 2026-01-01T00:00:00Z",
"contentType": "CSV"
}
GET /services/data/vXX.0/jobs/query/{jobId} -> state: JobComplete
GET /services/data/vXX.0/jobs/query/{jobId}/results?maxRecords=500000
-> response header Sforce-Locator: <next>; repeat with &locator=<next> until null