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 results
  • bench/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-loop or worker;
  • resource profile — normal (interactive ClickHouse policy) or bulk (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.

SettingDefaultDescription
WORKER_OBS_COUNT_LIMITunset (infinite)Above this result size, requests use worker execution
BULK_OBS_COUNT_LIMITunset (infinite)Above this result size, requests use the bulk resource profile
SYNC_MAX_OBSERVATIONS5000000Maximum observations in one synchronous response
WORKERS_ENABLEDtrueEnable worker execution, local pool and remote dispatch
WORKER_POOL_ENABLEDtrueEnable the local worker pool when workers capacity is enabled
WORKER_POOL_COUNTmin(4, availableParallelism - 1)Maximum workers per sxs process
WORKER_POOL_QUEUE_SIZE20Maximum queued worker jobs
WORKER_POOL_MAX_PER_SPACE1Maximum concurrently running worker jobs per space
WORKER_POOL_MAX_JOBS20Jobs per worker before recycling it
WORKER_POOL_MEMORY_MB512Maximum old-generation heap per worker

Global environment configuration:

WORKER_OBS_COUNT_LIMIT=10000
BULK_OBS_COUNT_LIMIT=50000
SYNC_MAX_OBSERVATIONS=5000000
WORKERS_ENABLED=true
WORKER_POOL_ENABLED=true
WORKER_POOL_QUEUE_SIZE=20
WORKER_POOL_MAX_PER_SPACE=1
WORKER_POOL_MAX_JOBS=20
WORKER_POOL_MEMORY_MB=512

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:

{
  "workerObsCountLimit": 10000,
  "bulkObsCountLimit": 50000,
  "syncMaxObservations": 5000000
}

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.

413 Payload Too Large
Content-Type: application/json

{
  "message": "Synchronous bulk limit exceeded (...). Use an asynchronous export."
}

Clients can request an export directly with:

GET /{space}/sdmx/data/dataflow/ECB/EXR/1.0.5?format=json
Prefer: respond-async

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 limit is lower than or equal to both thresholds stays main-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 worker when the selected size exceeds the worker threshold;
  • resource profile is bulk when 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

Normal profileBulk profile
ClickHouse tableDistributed table when the cluster is shardedLocal table on one node
ThreadsNormal cluster parallelismmax_threads = 1
Execution speedUnrestrictedCapped by max_execution_speed
Query cacheEligibleBypassed
ConcurrencyNormalThrottled by running bulk-resource jobs
Multi-dataset requestsAllowedMore than one bulk query is rejected

Current execution policy

Execution modeConditions
main-loopSmall requests, native formats, multi-dataset requests, worker disabled
workerJSON/SDMX-CSV, one dataset, worker enabled, and size/history requires it

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:

Concurrent worker jobsmax_execution_speed
Fewer than 510M rows/s
Fewer than 101M rows/s
10 or more500K rows/s

Each bulk query also uses:

max_threads = 1
timeout_before_checking_execution_speed = 0.001

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, datasetName and the dataset reference;
  • obsMode (obs or series);
  • executionMode (main-loop or worker);
  • resource (normal or bulk);
  • format, status, queuedAt and executionStartedAt;
  • the ClickHouse query and execution settings;
  • obsCount, seriesCount, runningBulks, hostname and nodes;
  • workerId, queueWaitMs, builderEndedAt, endedAt, durationMs;
  • outputBytes, worker heap usage, cancellation and error details.

Statuses are:

pending -> running -> done
                      |- failed
                      \- cancelled

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 includeHistory or updatedAfter;
  • 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

HTTP request
  └─ Data.getData()
      └─ filterObservations()
          ├─ filterAllDimensionsObservations()
          └─ filterSeries()
              ├─ main-loop → observationsGen
              └─ worker → workerJob
                  └─ { op: 'workerJob', job }
                      └─ WorkerPool.run()
                          ├─ queue / per-space limits
                          ├─ 429 when the queue is full
                          └─ worker
                              ├─ executes the observation query
                              ├─ executes history/updatedAfter queries when needed
                              ├─ runs the SDMX data builder
                              ├─ serializes JSON or CSV
                              └─ streams chunks back
                                  └─ main writes to the HTTP response

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:

worker -> chunk
main   -> res.write(chunk)
main   -> wait for drain if needed
main   -> ack
worker -> next chunk

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 (default 20).
  • When the queue is full, run() throws an HTTPError with code 429.
  • Active jobs are not counted in the queue length.
  • Each space can have at most WORKER_POOL_MAX_PER_SPACE running 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_JOBS jobs (default 20).
  • Each worker is created with resourceLimits.maxOldGenerationSizeMb set from WORKER_POOL_MEMORY_MB (default 512).
  • 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:

{
  "enabled": true,
  "workers": 2,
  "busy": 1,
  "queued": 0,
  "activeBySpace": { "collect": 1 },
  "started": 12,
  "completed": 10,
  "failed": 1,
  "cancelled": 1,
  "recycled": 2,
  "rejected": 0,
  "maxJobs": 20,
  "memoryLimitMb": 512,
  "workerStats": [
    {
      "id": 1,
      "busy": true,
      "jobs": 7,
      "heapUsedMb": 42.1,
      "heapLimitMb": 512,
      "startedAt": "2026-10-28T14:00:00.000Z",
      "lastJobAt": "2026-10-28T14:02:10.000Z",
      "currentJob": {
        "queryId": "…",
        "spaceId": "collect",
        "format": "csv",
        "startedAt": "2026-10-28T14:03:00.000Z"
      }
    }
  ]
}

rejected counts queue-full 429 responses. Queue-full responses also include Retry-After: 5.

Cancellation

When the client disconnects:

  1. the pool sends { type: 'cancel' } to the worker;
  2. the worker aborts the builder signal;
  3. the ClickHouse stream is destroyed;
  4. the worker response is destroyed;
  5. the worker sends cancelled;
  6. 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:

DataBuilder
  ↓
ModelJSONOut / ModelCSVOut
  ↓
service JSONOut / CSVOut
  ↓
worker response sink

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:

PathFormatDurationThroughputEvent-loop p99Fast query p50
Main threadJSON5.18 s193k obs/s21.6 ms144 ms
WorkerJSON5.46 s183k obs/s2.29 ms98 ms
Main threadSDMX-CSV11.05 s90.5k obs/s14.8 ms348 ms
WorkerSDMX-CSV7.71 s130k obs/s2.23 ms97 ms

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:

FormatDurationThroughputEvent-loop p99Fast query p50
JSON21.39 s234k obs/s2.17 ms97.6 ms
SDMX-CSV33.73 s148k obs/s2.27 ms97.4 ms

For comparison:

Format1M duration5M durationNotes
SDMX-CSV11.05 s (worker: 7.71 s)54.22 sMain-thread 5M value
Native CSV0.43 s1.76 s342 MB at 5M
Parquet0.27 s1.11 s24 MB at 5M

The 1M worker runs include worker startup.

Full benchmark methodology and raw results are in bench/BULK_BASELINE.md.

Benchmarks

Run the fallback baseline:

yarn bench:bulk
BENCH_BULK_FORMAT=csv yarn bench:bulk
ALLOW_NATIVE_CSV=true BENCH_BULK_FORMAT=csv yarn bench:bulk
BENCH_BULK_FORMAT=parquet yarn bench:bulk

Run the worker path:

BENCH_WORKERS=true BENCH_BULK_FORMAT=json yarn bench:bulk
BENCH_WORKERS=true BENCH_BULK_FORMAT=csv yarn bench:bulk

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-After when the queue is full
  • src/server/tests/workerPoolModes.test.js
    • series, includeHistory, updatedAfter and series history modes through real workers
    • per-worker metrics
    • worker recycling
  • 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-Range counting series
  • src/server/tests/bulkZero.test.js
    • zero BULK_OBS_COUNT_LIMIT behaviour
  • 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:

yarn test src/server/tests/workerPool.test.js
yarn test src/server/tests/workerPoolModes.test.js
yarn test src/server/tests/obsCount.test.js
BENCH_BULK=1 BENCH_WORKERS=true BENCH_BULK_FORMAT=csv yarn bench:bulk
BENCH_BULK=1 BENCH_WORKERS=true BENCH_BULK_CANCEL=true BENCH_BULK_OBS=100000 \
  BENCH_BULK_FORMAT=json yarn bench:bulk

Implementation

This section summarizes the end-to-end implementation.

Request flow

HTTP request
  └─ Data.getData()
      └─ filterObservations()
          ├─ filterAllDimensionsObservations()
          └─ filterSeries()
              ├─ main-loop → normal response builder
              └─ worker → workerJob
                  └─ { op: 'workerJob', job }
                      └─ WorkerPool.run()

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 / normal when limit is below or equal to both thresholds;
  • main-loop / normal when the dataset total is below both thresholds;
  • main-loop / normal when the selected count is below both thresholds;
  • main-loop / normal for dimension-group-only requests;
  • worker when the selected count exceeds the worker threshold;
  • bulk resource 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_jobs record 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:

max_threads = 1
timeout_before_checking_execution_speed = 0.001
max_execution_speed:
  fewer than 5 running worker jobs  → 10M rows/s
  fewer than 10 running worker jobs → 1M rows/s
  10 or more                      → 500K rows/s

It records the job in the per-space worker_jobs collection with:

  • queryId, datasetId, datasetName and ref;
  • obsMode (obs or series);
  • executionMode and resource;
  • format, status, queuedAt and startedAt;
  • the SQL query, limit, offset, obsCount and seriesCount;
  • 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 429 with Retry-After;
  • WORKER_POOL_MAX_PER_SPACE limits concurrent jobs per space;
  • workers are recycled after WORKER_POOL_MAX_JOBS or 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:

  1. marks the worker job running;
  2. opens the ClickHouse stream with the job's resource settings;
  3. records query1_EndedAt;
  4. runs the SDMX data builder;
  5. executes history/updated-after event queries when needed;
  6. serializes JSON or SDMX-CSV;
  7. streams output in chunks to the main thread;
  8. marks the record done, failed or cancelled.

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/offset count 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_jobs collection;
  • the sxsWorkerJobs RPC service;
  • request logs with executionMode and resource;
  • worker metrics from /healthcheck and /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_threads pool
  • 20-job queue with 429 when full
  • JSON and non-native SDMX-CSV offload
  • series, includeHistory and updatedAfter
  • 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 /healthcheck and /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-After is returned with queue-full 429 responses;
  • 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.