Bulk resource profile and worker jobs
This document describes how sxs protects ClickHouse from large synchronous
extracts, how the bulk resource profile differs from the normal profile,
and how worker execution is applied to synchronous requests.
Related documentation:
- Execution modes and resource profiles — execution modes, resource profiles and capacities
bench/BULK_BASELINE.md— bulk download benchmark methodology and resultsbench/SERIES_BENCH.md— series query benchmark and current results- Output formats — format selection and native formats
Why the bulk resource profile exists
Interactive queries must stay fast while other clients download large datasets. A single unrestricted ClickHouse query can consume cluster resources and, on the Node side, monopolize the event loop.
sxs therefore separates:
- execution mode —
main-looporworker; - resource profile —
normal(interactive ClickHouse policy) orbulk(throttled ClickHouse policy); - delivery — synchronous response or asynchronous export.
The bulk resource profile is selected by BULK_OBS_COUNT_LIMIT. Worker execution
is selected by WORKER_OBS_COUNT_LIMIT and by includeHistory /
updatedAfter. The two decisions are independent.
See Execution modes and resource profiles for the complete model.
Configuration
See Configuration and settings for the complete variable and settings reference, including global variables and space-overridable settings.
Global environment configuration:
The worker settings are process-global. They are read once when the pool is created; space-level values are not used for these six variables.
Thresholds can also be set per space in the tenant configuration:
Synchronous cap
SYNC_MAX_OBSERVATIONS caps the number of observations returned by one
synchronous data request. When the selected result exceeds the cap, sxs returns
413 Payload Too Large.
Clients can request an export directly with:
The server returns 202 Accepted and creates an asynchronous export. Exports
use EXPORT_MAX_OBSERVATIONS instead and bypass the synchronous cap. The
synchronous cap can be set per space with syncMaxObservations.
Classification
For SDMX-JSON and SDMX-CSV requests:
- a dimension-group-only request stays
main-loop/normal; - a request whose
limitis lower than or equal to both thresholds staysmain-loop/normal; - a request whose dataset total is lower than or equal to both thresholds stays
main-loop/normal; - otherwise the selected result is counted; for a limited request the selected page is the classification size;
- execution mode is
workerwhen the selected size exceeds the worker threshold; - resource profile is
bulkwhen the selected size exceeds the bulk threshold; - for worker or bulk requests, the full filtered count is recorded for statistics
and
Content-Range.
All-dimensions requests apply limit, offset and sort in both normal and
bulk profiles. Without a limit, the full filtered result is returned.
Normal series requests always count the filtered observations because a series
limit/offset pages series rather than observations. Series limit and
offset are honored but never capped.
includeHistory and updatedAfter force worker execution. They do not force the
bulk resource profile: the resource profile still depends on the result size.
Resource policy
Current execution policy
When worker offload is not possible, the request falls back to the main loop but keeps its resource profile. The bulk fallback still uses the local table and the bulk ClickHouse settings.
Bulk concurrency is measured from bulk-resource worker jobs started within the last eight hours. The execution-speed cap is reduced as concurrency rises:
Each bulk query also uses:
Only jobs with resource: bulk count toward this throttle. Worker jobs with
resource: normal do not consume bulk ClickHouse capacity.
Worker jobs
Worker job details are recorded in the per-space worker_jobs collection. Each
record includes:
queryId,datasetId,datasetNameand the dataset reference;obsMode(obsorseries);executionMode(main-looporworker);resource(normalorbulk);format,status,queuedAtandexecutionStartedAt;- the ClickHouse query and execution settings;
obsCount,seriesCount,runningBulks,hostnameandnodes;workerId,queueWaitMs,builderEndedAt,endedAt,durationMs;outputBytes, worker heap usage, cancellation and error details.
Statuses are:
Records are retained for 120 days. Pending and running bulk-resource records are
used by getBulkResourceSettings() to throttle ClickHouse bulk concurrency.
Records created before the execution-mode split used runningMode and are read
as worker / bulk for backward compatibility.
Observation limit and pagination
The worker and bulk thresholds are classification thresholds, not result caps.
All-dimensions requests apply the requested limit, offset and sort in both
normal and bulk profiles. Without a limit, the full filtered result is
returned.
For series requests with limit or offset, Content-Range counts series,
not observations. The header reports the selected series page and the total
distinct filtered series. For all-dimensions requests, Content-Range counts
observations.
Native formats bypass classification
These formats are produced directly by ClickHouse and bypass both the JavaScript SDMX builder and the worker pool:
- native CSV (
ALLOW_NATIVE_CSV=true/allowNativeCsv: true) - Parquet
- Arrow
- ArrowStream
- Protobuf
They also bypass the normal/bulk resource classification and keep the normal
distributed-table path. They are still subject to SYNC_MAX_OBSERVATIONS.
SDMX JSON and SDMX-CSV when native CSV is disabled use the JavaScript builder
and can use worker execution.
Worker execution path
Worker-eligible SDMX JSON and non-native SDMX-CSV requests are processed by a
bounded worker path. The worker may be local (node:worker_threads in the same
process) or remote (a wxs worker through the Mongo queue and callback).
Scope
Worker offload is currently enabled for:
- requests above
WORKER_OBS_COUNT_LIMIT; - all-dimensions and series requests with
includeHistoryorupdatedAfter; - JSON or SDMX-CSV output;
- one dataset per request;
- a configured and enabled worker pool.
The worker runs history/updated-after event queries itself. The following still use the main-loop or direct ClickHouse path:
- native CSV, Parquet, Arrow, ArrowStream and Protobuf;
- dimension-group-only requests;
- multi-dataset requests;
- requests where the worker pool is disabled or unavailable.
A multi-dataset request that contains a bulk-resource query or uses
history/updated-after is rejected with 406.
Execution flow
The worker executes the ClickHouse query itself, so observation rows never cross the thread boundary.
Main thread responsibilities
- HTTP request/response lifecycle
- queueing and per-space fairness
- applying response headers
- writing chunks to the client
- backpressure acknowledgements
- worker-job audit updates
- worker lifecycle and replacement
Worker responsibilities
- ClickHouse observation stream execution
- ClickHouse event/history stream execution
- row parsing
- SDMX data building
- JSON/SDMX-CSV serialization
- output buffering
- cancellation handling
Backpressure
The worker sends final response bytes in chunks. The main thread writes each
chunk and waits for drain when needed before acknowledging it:
The worker buffers output up to 64 KB before sending it, which is especially important for CSV because the serializer emits one row at a time.
This propagates backpressure through the worker to the ClickHouse stream and keeps memory bounded.
Queueing
The queue is in memory and per sxs process.
- Maximum queued jobs:
WORKER_POOL_QUEUE_SIZE(default20). - When the queue is full,
run()throws anHTTPErrorwith code429. - Active jobs are not counted in the queue length.
- Each space can have at most
WORKER_POOL_MAX_PER_SPACErunning jobs by default.
Because the queue is local, multiple sxs replicas each have their own queue. There is no distributed queue at this stage.
Worker recycling and memory limits
- Each worker is recycled after
WORKER_POOL_MAX_JOBSjobs (default20). - Each worker is created with
resourceLimits.maxOldGenerationSizeMbset fromWORKER_POOL_MEMORY_MB(default512). - A worker is also recycled when its heap usage reaches 90% of that limit.
- Workers that fail, exit unexpectedly or are cancelled are terminated and replaced for the next job.
- Recycling avoids retaining large builder maps and output buffers indefinitely.
Worker metrics
The pool exposes metrics through /healthcheck and /ready:
rejected counts queue-full 429 responses. Queue-full responses also include
Retry-After: 5.
Cancellation
When the client disconnects:
- the pool sends
{ type: 'cancel' }to the worker; - the worker aborts the builder signal;
- the ClickHouse stream is destroyed;
- the worker response is destroyed;
- the worker sends
cancelled; - the pool releases the worker.
If the worker does not respond within five seconds, it is terminated.
Queued requests are also cancelled. Client close/abort listeners remove them from the queue, and a 250 ms queue sweep handles missed close events. The cancellation stress benchmark aborts 20 concurrent worker requests and verifies that the queue drains and workers are released.
Worker failure
On worker error or unexpected exit:
- the current HTTP response is rejected if headers have not been sent;
- otherwise the response is destroyed;
- the worker is removed;
- a replacement worker can be created for the next job.
On SIGTERM or SIGINT, the pool rejects queued jobs, terminates all workers
and exits the process gracefully.
Worker startup
Workers are created lazily on the first worker job. The first request in a process therefore pays the worker startup and initialization cost.
Workers initialize:
- config;
- config provider;
- MongoDB;
- ClickHouse;
- settings;
- models.
For isolated benchmarks and tests, workerData can override the config and
member list.
Output parity
The worker uses the same output stack as the main thread:
This preserves the JSON/CSV envelope, headers and payloads.
The dataset passed to the worker includes its full metadata and its _id is
converted to a string. Worker output was compared against the main-thread path
for the same fixtures: data payloads and CSV output match, with only
request-specific metadata (meta.id, prepared, self link) differing.
Performance
1M observations, local test environment:
Worker SDMX-CSV is faster than the main-thread path. Worker JSON loses about 5% throughput to cross-thread transfer but removes the event-loop impact.
5M observations through workers:
For comparison:
The 1M worker runs include worker startup.
Full benchmark methodology and raw results are in bench/BULK_BASELINE.md.
Benchmarks
Run the fallback baseline:
Run the worker path:
The benchmark uses isolated test-* MongoDB/ClickHouse databases and removes
them afterwards.
Tests
Relevant tests:
src/server/tests/workerPool.test.js- queue default is 20
- JSON/CSV delegation
- 429 and
Retry-Afterwhen the queue is full
src/server/tests/workerPoolModes.test.js- series,
includeHistory,updatedAfterand series history modes through real workers - per-worker metrics
- worker recycling
- series,
src/server/tests/bulkAlways.test.js- small normal series stay in the main loop
- history requests are forced into a worker
- history requests below the bulk threshold use
resource: normal - series pagination and
Content-Rangecounting series
src/server/tests/bulkZero.test.js- zero
BULK_OBS_COUNT_LIMITbehaviour
- zero
src/server/tests/bulkBaseline.test.js- optional event-loop and throughput benchmark
- cancellation stress mode: 20 concurrent worker requests aborted in flight
src/server/tests/obsCount.test.js- normal/bulk classification and existing bulk behaviour
- multi-dataset bulk rejection
- CSV, series, PIT, range and multilingual suites
- output parity and formatter regressions
Run:
Implementation
This section summarizes the end-to-end implementation.
Request flow
The relevant code paths are in
src/server/models/resources/data.js,
src/server/models/resources/workers/workerPool.js and
src/server/services/sdmx/output/.
Classification
All-dimensions requests use selectModes():
main-loop/normalwhenlimitis below or equal to both thresholds;main-loop/normalwhen the dataset total is below both thresholds;main-loop/normalwhen the selected count is below both thresholds;main-loop/normalfor dimension-group-only requests;workerwhen the selected count exceeds the worker threshold;bulkresource when the selected count exceeds the bulk threshold.
Series requests always count filtered observations and apply the same two
thresholds. includeHistory and updatedAfter force worker execution but do
not change the resource profile by themselves.
WORKER_OBS_COUNT_LIMIT and BULK_OBS_COUNT_LIMIT unset mean infinite
thresholds. Setting both to 0 forces every non-empty request into worker and
bulk. Multi-dataset requests containing a bulk-resource query or using history
are rejected with 406.
The legacy runningMode field in old records is read as worker / bulk. New
records use executionMode and resource.
Normal profile policy
The normal profile:
- uses the distributed ClickHouse table when the cluster is sharded;
- uses normal ClickHouse parallelism;
- is eligible for the observation query cache;
- does not create a
worker_jobsrecord when running in the main loop; - does not consume bulk concurrency.
Bulk profile policy
The bulk profile calls getBulkResourceSettings(), which counts only pending and
running worker_jobs records with resource: bulk from the last eight hours and
returns:
It records the job in the per-space worker_jobs collection with:
queryId,datasetId,datasetNameandref;obsMode(obsorseries);executionModeandresource;format,status,queuedAtandstartedAt;- the SQL query,
limit,offset,obsCountandseriesCount; - ClickHouse settings and
runningBulks; - hostname, node names and worker information;
- runtime fields such as
executionStartedAt,queueWaitMs,builderEndedAt,endedAt,durationMs, output bytes, heap usage, cancellation and errors.
All-dimensions bulk queries read from the local ClickHouse table. Series bulk
queries use the local table with series pagination. The worker executes the
query with queryStreamLB().
Worker pool
The worker pool is a bounded set of node:worker_threads:
- workers are reused across jobs;
- the queue is bounded by
WORKER_POOL_QUEUE_SIZE; - a full queue returns
429withRetry-After; WORKER_POOL_MAX_PER_SPACElimits concurrent jobs per space;- workers are recycled after
WORKER_POOL_MAX_JOBSor on heap pressure; - failed workers are terminated and replaced;
- queued and active jobs are cancelled when the client disconnects;
- the pool is closed on
SIGTERM/SIGINT.
Worker execution
Each worker initializes its own config, MongoDB, ClickHouse, settings and models. For every job it:
- marks the worker job
running; - opens the ClickHouse stream with the job's resource settings;
- records
query1_EndedAt; - runs the SDMX data builder;
- executes history/updated-after event queries when needed;
- serializes JSON or SDMX-CSV;
- streams output in chunks to the main thread;
- marks the record
done,failedorcancelled.
The worker sends output in 64 KB chunks. The main thread applies backpressure and acknowledges each chunk, so a slow client slows the ClickHouse stream instead of growing memory.
Main-thread fallback
If a worker cannot be used, the query runs on the main thread with the same
resource profile. For bulk, the worker_jobs record and ClickHouse bulk
settings are still used.
This happens when workers are disabled, the output format is not JSON/CSV, there are multiple datasets, the request is dimension-group-only, or the worker pool is unavailable. The fallback preserves correctness but does not protect the event loop.
Content-Range
- All-dimensions responses count observations.
- Series responses with
limit/offsetcount distinct series. - Series responses without pagination do not emit
Content-Range. - Native Parquet and native CSV use the same series count through their output context.
- SDMX JSON and SDMX CSV use
processXRange().
Native formats
Native CSV, Parquet, Arrow, ArrowStream and Protobuf:
- bypass the worker pool;
- bypass the JavaScript SDMX builder;
- stream directly from ClickHouse;
- bypass normal/bulk resource classification;
- keep the normal distributed-table path.
They still use their native pagination and range headers, and remain subject to
SYNC_MAX_OBSERVATIONS.
Synchronous cap and exports
Worker responses are still synchronous HTTP responses. SYNC_MAX_OBSERVATIONS
is checked before execution and returns 413 when the result is too large.
Requests above that limit should use an asynchronous export.
Observability
Bulk resource and worker execution are visible through:
- the per-space
worker_jobscollection; - the
sxsWorkerJobsRPC service; - request logs with
executionModeandresource; - worker metrics from
/healthcheckand/ready; - per-worker job and heap counters.
Implementation phases
Phase 1 — baseline (done)
- event-loop metrics p50/p95/p99/max
- synthetic benchmark dataset and DSD
- JSON, SDMX-CSV, native CSV and Parquet measurements
- CSV formatter optimization
- documentation
Phase 2 — worker offload (done)
node:worker_threadspool- 20-job queue with 429 when full
- JSON and non-native SDMX-CSV offload
- series,
includeHistoryandupdatedAfter - ack-based backpressure
- cancellation, including queued requests
- worker metrics, recycling and memory limits
- native-format bypass
- worker benchmarks, cancellation stress tests and unit tests
Phase 3 — hardening and multi-dataset policy (done)
- multi-dataset requests are never handed to workers;
- a multi-dataset request containing any bulk dataset is rejected with
406; - per-worker job and heap metrics are exposed through
/healthcheckand/ready; - workers recycle on job count and heap pressure;
- cancellation stress covers queued and active requests;
- automated tests cover series,
includeHistory,updatedAfter, metrics and recycling; Retry-Afteris returned with queue-full429responses;- the pool terminates workers on
SIGTERM/SIGINT.
Large multi-dataset exports must be split by the client or moved to Phase 4.
Phase 4 — asynchronous export
For very large or multi-hour downloads, create an export instead of holding the HTTP request open. The export is written to object storage and downloaded later. See Asynchronous exports for the API, queue and limits.
