Skip to content

Add load tests, a browser swarm and committed benchmark results - #4055

Open
T4rk1n wants to merge 17 commits into
devfrom
feat/benchmarks
Open

T4rk1n wants to merge 17 commits into
devfrom
feat/benchmarks

Conversation

@T4rk1n

@T4rk1n T4rk1n commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Load tests for streaming and callbacks, a headless-browser swarm for large runs, and CI that commits the numbers to the repo, with a short table in the README.

Changes

  • benchmarks/streaming/: how many browsers each server setup can stream to (Flask/gunicorn, FastAPI and Quart on uvicorn, 1 or 4 workers). Simulated browsers follow the renderer's StreamClient and the count climbs until p95 frame latency or errors give out.
  • benchmarks/callbacks/: the same sweep for plain callbacks, HTTP vs websocket, by backend (Flask HTTP only; FastAPI and Quart both). --kind async and --work-ms add per-call work.
  • benchmarks/loadkit.py: the plumbing both share. It runs the server and the clients on separate CPUs, flags points where the clients ran out of CPU, and makes the server import the checkout under test, not the installed dash.
  • benchmarks/swarm/: real headless Chromium users (Playwright), many per machine and many machines, against a deployed app. Users click an HTTP callback, a websocket callback or a stream, timed in the page from click to DOM update, so machines only share a start time, not clocks.
    • Agents run locally or over SSH in a Docker image. They report mergeable histograms.
    • Steps stop when the server saturates or when the swarm stops delivering its load: failed agents or users, agents over 85% CPU, late starts.
    • Meant for a one-off cloud run; see benchmarks/README.md.
  • benchmarks/publish.py + .github/workflows/benchmarks-publish.yml: one place for the numbers, in this repo.
    • Weekly and on dispatch only, CI measures on dev. It opens a pull request that updates benchmarks/results/ and the README table only when the numbers moved significantly: a load test's capacity changes step, or a renderer median moves by over 25% and 5 ms. The pull request lists what moved.
    • The per-PR renderer regression comment (benchmarks.yml) is unchanged.
    • benchmarks/results/report.json has every chart as a Plotly figure plus the tables, for the docs to render with dcc.Graph. The raw numbers and their history sit next to it.
    • The repo needs "Allow GitHub Actions to create and approve pull requests" turned on. A pull request opened with GITHUB_TOKEN starts no checks, so close and reopen it before merging.
    • The README table says "No published run yet" until the first run.

Numbers

Callbacks, sync, 1 worker, 8-core laptop:

p95 at 1000 browsers p95 at 4000
Flask HTTP 3.7 ms 4.6 s (saturated from 2000)
FastAPI HTTP / websocket 1.2 / 0.9 ms 165 / 27 ms
Quart HTTP / websocket 1.9 / 1.0 ms 511 / 469 ms

With 4 workers no setup saturated at 4000 browsers; the swarm is how to find those limits. The multi-worker Redis streaming numbers need #4054.

Tests

  • Unit tests for the publisher (results, history, figures, README table) and for histogram merging.
  • A report from real runs rendered in a Dash app, headless: all 9 figures draw, no console errors, and the trend dropdown switches scenario.
  • Every load test and every setup ran locally.
  • The swarm ran locally and through a fake ssh/docker fan-out. One agent with 50 users measured about 0.05 core and up to 170 MB per user.
  • The swarm's Docker image builds, and one agent in it ran 10 real browsers against a local app with no errors.

T4rk1n added 4 commits October 7, 2026 12:10
benchmarks/streaming/ measures how many browsers each server setup can
stream to (Flask/gunicorn, FastAPI and Quart on uvicorn, 1 or 4 workers),
with simulated browsers that follow the renderer's StreamClient.
benchmarks/publish.py builds a static site from the renderer timings and
the streaming sweep (embeddable chart pages, raw data with history,
shields badges), and benchmarks-publish.yml pushes it to gh-pages from dev.
benchmarks/callbacks/ sweeps browser counts for plain callbacks over HTTP
and over the websocket on Flask (HTTP only), FastAPI and Quart, 1 and 4
workers, recording round trip, throughput, errors and CPU. The server and
client plumbing it shares with the streaming test moves to
benchmarks/loadkit.py.
benchmarks/swarm/ drives real Chromium users (Playwright) against a
deployed app: plain HTTP callbacks, websocket callbacks and streaming,
timed in the page from click to DOM update. Agents run locally or on remote
hosts over SSH in a Docker image, start together at a shared wall-clock
time, and report mergeable histograms; steps stop when the server
saturates or when the swarm stops delivering its load (failed agents or
users, agents over 85% CPU, late starts).
The benchmark site gains a callbacks section: browsers served per setup
coloured by transport, p95 round trip for 1 and 4 workers (websocket
dashed), server CPU per 1,000 calls a second, the full table, badges and
data with history. The publish workflow runs the callback sweep weekly and
on demand, like the streaming one.
@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Dash performance benchmarks

✅ all within thresholds

scenario metric p90 (ms) median growth baseline p90 note
✅ callback_chain chain_ms 539.4 512.5 1.05x 595.4
✅ callback_chain graph_ms 2.4 2.4 1.0x 2.1
✅ callback_fanout fanout_ms 94.0 83.5 0.87x 88.3
✅ callback_fanout_children_update fanout_ms 149.4 135.2 0.95x 164.8
✅ deep_nesting render_ms 56.4 53.8 1.01x 61.1
✅ full_children_replace replace_ms 167.4 104.7 2.9x 161.2
✅ initial_render_large render_ms 656.3 601.0 0.89x 697.8
✅ initial_render_small render_ms 112.4 93.6 1.05x 102.7
✅ patch_append_nested append_ms 137.3 83.1 2.59x 127.2
✅ patch_append_toplevel append_ms 129.7 87.0 2.42x 165.8
✅ patch_scalar_update_large update_ms 133.6 129.8 0.98x 144.7
✅ rerender_existing_subtree rerender_ms 119.0 105.0 0.85x 121.0
✅ wildcard_all_resolve wildcard_ms 340.3 317.6 0.96x 313.4
✅ wildcard_all_resolve graph_ms 1.4 1.4 1.0x 1.2

growth = late-third / early-third per-op time; ~1 is flat, a large value means the per-op cost scales with accumulated state.

machine scale vs baseline: 0.95x - divided out of the baseline ratios so they compare like for like (the absolute warn/fail ceilings are left un-scaled); calibrated on initial_render_small.

T4rk1n added 2 commits October 7, 2026 13:51
Share the sweep loop between the streaming and callback runners
(loadkit.sweep), split the callback client's and swarm agent's long loops
into small steps, write the swarm report outside the event loop, dedupe
the site builder's sections and literals, run the agent image as its
unprivileged user, and pin the third-party setup-chrome action to a
commit. The site output is byte-identical for the same inputs.
@camdecoster
camdecoster marked this pull request as draft October 8, 2026 19:32
The playwright/python image ships the browsers but not the Python
package, so the agent failed to import it.
The numbers live in benchmarks/results/ for the docs to render
(report.json holds every chart as a Plotly figure), and a short table in
README.md shows how many browsers each server setup keeps interactive.
The workflow now runs weekly and opens a pull request with the update.
The weekly run commits a load test only when a setup's capacity changes
step, and the renderer only when a median moves by over 25% and 5 ms.
The pull request lists what moved.
Times dash._utils.to_json on a large figure alone and next to one value
orjson cannot serialize (issue #4065), each engine in its own process.
Published weekly with the other benchmarks.
@T4rk1n T4rk1n changed the title Add load tests, a browser swarm and a public benchmark site Add load tests, a browser swarm and committed benchmark results Nov 5, 2026
@T4rk1n
T4rk1n marked this pull request as ready for review November 5, 2026 15:19

@KoolADE85 KoolADE85 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like this benchmark tooling will be bundled with the published dash whl. Is that intended? Maybe we should omit benchmark code as we do with tests?

Comment thread benchmarks/README.md

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The load tests import aiohttp and require gunicorn, but these don't come with a stock venv. We should have a "how to get benchmark" section that says exactly what users need to install.. Maybe

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a Setup section at the top of the README with the exact installs for each part (renderer, load tests, swarm), plus Redis and Chrome notes. Checked it by running both load tests in a fresh venv set up from those lines only.

@T4rk1n

T4rk1n commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

On the wheel: dev already fixed that (setup.py now packages only dash.*, with tests/unit/test_packaging.py guarding it), and this branch now has dev merged in, so the benchmarks stay out of the whl.

A sweep that broke, or a point where browsers never loaded, no longer
reads as a lower bound; the load scripts exit 1 so CI keeps the old
numbers. The renderer job publishes a complete gate-failing run but not a
partial one, and carries scenario descriptions to the publish job.

The streaming simulator picks a fresh downlinkId and cursor per click
like the renderer, callback work is CPU time, CPU pinning stays inside the
allowed set without leaking the server, and CPU sampling starts at the
measure window.
@sonarqubecloud

Copy link
Copy Markdown

Comment thread .ai/PERFORMANCE.md
Comment on lines 171 to +327
## Findings

Numbers below are from `ubuntu-latest`-class hardware, production bundle, React
18. They move with the machine; trust the **shape** (flat vs growing, and which
function dominates), not the absolute ms.

### Snapshot (median per-op)

| scenario | median | growth | reading |
|--|--:|--:|--|
| initial_render_small (200 rows) | ~45 ms | 1.0x | fine |
| initial_render_large (3000 rows) | ~240 ms | 1.0x | linear in node count, expected |
| deep_nesting (120 deep) | ~27 ms | 1.0x | fine |
| patch_append_toplevel | ~52 ms | ~2x | flat enough; residual is shared O(total) traversal |
| patch_append_nested | ~54 ms | ~2.8x | same; the [[nested append fix]] keeps re-hydration O(appended) |
| patch_scalar_update_large (3000) | ~80 ms | ~0.8x | flat - in-place value change |
| callback_fanout (1 -> 300) | ~45 ms | 1.0x | fine |
| callback_chain (100 deep) | ~440 ms | 1.0x | ~100 sequential dispatches; inherent |
| wildcard_all_resolve (ALL over 400) | ~140 ms | 1.0x | was ~580 ms (O(n²)); now O(n), see below |
| full_children_replace (200 -> 2000) | ~50 ms | ~3x | linear in the list it rebuilds; was ~18x (O(n^2)), see below |
| rerender_existing_subtree (400 rows) | ~50 ms | 1.0x | was ~1200 ms (O(n^2)); see below |

### 1. Wildcard (ALL / MATCH) resolution — was O(n²), now O(n) [fixed]

Profiling `wildcard_all_resolve` (one input change, `Output({...: ALL})` over
400 components) originally put ~45% of the time in ramda `_equals` +
`_functionName`. Root cause: `getPath` for a pattern-matching (dict) id did a
**linear** `find(propEq(values, 'values'), keyPaths)` over every component
sharing that id shape, and `propEq` is a **deep-equality** on the id-values
array. During an `ALL` resolution `getPath` is called once per resolved
component, so it was O(N) lookups × O(N) scan × O(k) equals ≈ **O(N²·k)**.

**Fix (`dash/dash-renderer/src/actions/paths.js`):** the paths table now
carries an `objIndex` - `{[keyStr]: {[valuesKey]: path}}`, where `valuesKey` is
`JSON.stringify(values)` - so `getPath` is an O(1) map lookup. `objs` stays an
ordered array because pattern matching (`resolveDeps`, `getAllPMCIds`) walks it
in order; `objIndex` is only for exact lookups. It's maintained inline in
`computePaths` (copy-on-write per keyStr, so re-resolving one chunk doesn't
rebuild the index for unrelated components) and extended incrementally in
`appendPaths`; a table without an index (empty initial state, test fixture)
makes `getPath` fall back to the linear scan, so the two never disagree.
Result: `wildcard_all_resolve` went **~580 ms → ~140 ms (≈4x)**, and the
`_equals`/`_functionName` frames left the profile. What remains is O(N) - one
`assocPath` per resolved output - which is inherent to writing N updates.

### 2. Patch append (post-fix) has no single hotspot

After the [[nested append fix]], profiling `patch_append_nested` shows the cost
spread across ramda `_path`/curry internals, React reconciliation, and redux
`useSelector` snapshots - the inherent O(total) *cheap* traversal (persistence
walk + callback crawl + element mapping), not the O(total) *re-hydration* that
the fix removed. There is no dominant frame to cut; flattening it further means
making those three traversals skip byref-unchanged subtrees (a bigger change).

### 3. Ramda currying overhead in the per-node hot loops [fixed]

Across every scenario the profiles showed ~10-15% in ramda's curry machinery -
`f1`/`f2`/`f3` (the arity dispatchers), `_isPlaceholder`, and curried `path`/
`pathOr`. It came from `crawlLayout` (utils.js), which runs the callback on
*every* component on *every* path recompute and callback gather, calling
curried `path(['props','children'], obj)` / `pathOr(...)` per node, plus the
`path(['props','id'], child)` in each crawl callback (`paths.js`,
`dependencies.js`). Replacing those with direct property access (`obj.props &&
obj.props.children`, etc.) and native array `concat` on the hot common path -
leaving the rare declared-`childrenProps` branch alone - cut `patch_append` by
~16% and initial render / wildcard by ~3-4% in a same-machine A/B. Low risk:
the crawled nodes are always plain component objects, so direct access is
equivalent to the curried `path`, just without the dispatch and placeholder
checks. When touching these traversals, prefer direct access over curried
ramda - the per-node multiplier makes it matter.

### 4. Re-rendering callback children was O(n^2) [fixed]

`full_children_replace` used to grow ~18x across a run and was written off as
the expected cost of not using `Patch`. It was not: every wrapper in a
re-rendered subtree dispatched `resetComponentState` from its `_newRender`
effect, and each dispatch re-runs every mounted wrapper's selector. 400 rows (1200
components) took 1219 store updates per click and ~1200 ms (#4121).

**Fix:** `resetDescendantHashes` checks `layoutHashes` first and only dispatches
when there is a hash under the wrapper's path to clear. The reducer also returns
the same object when nothing matches, and matches path segments, so resetting
`children,1` no longer clears `children,10`. Now 19 updates and ~50 ms.

`rerender_existing_subtree` covers the same-size case, which the first-render
guard from #3929 does not skip. `max_growth` on `full_children_replace` fails
the run when the per-click cost grows faster than the list (linear is ~3x).

### 5. Layouts deeper than ~250 nested components fail to serialize

`/_dash-layout` raises "Recursion limit reached" (the JSON encoder's recursion
limit) for a component tree nested deeper than ~254. The `deep_nesting`
scenario is capped at 120 to stay clear. Worth remembering before recommending
deeply-recursive layouts.

### 6. Components with `dashChildrenUpdate` scan every changed path [reduced]

`selectDashProps` runs for every mounted component on every store update. For a
component type that sets `dashChildrenUpdate` (`dcc.Tabs`, several DMC types),
`determineChangedProps` walks all of `layoutHashes`, which gains one entry per
path whose props ever changed and never shrinks: O(flagged components x changed
paths) per store update. `callback_fanout_children_update` covers it.

`isFirstLevelPropsChild` used to split both paths for each entry, and was the
top frame of that scenario (with `determineChangedProps`, 51% of CPU with 50
tabs). It now rejects unrelated paths with `isPathOrDescendant` before any
allocation, which brings that down to 9%. It is still a scan, just a cheap one.
The scenario mounts 200 tabs so that going back to the old scan (about 4x
slower there) fails the baseline gate. A prefix index would make
it O(1) per component, but rebuilding it whenever `layoutHashes` changes costs
about twice one scan, so it would slow down the common case of a single
`dcc.Tabs`. An index maintained incrementally in the reducer would avoid that.

### 7. One non-native value sends the whole response down plotly's slow path (#4065)

With orjson, `to_json_plotly` tries `orjson.dumps` on the whole response. If
any value is not orjson-native (a component, a `go.Figure` object, a
`pd.Timestamp`), it discards the attempt, walks everything in Python with
`clean_to_json_compatible`, then dumps again. A `go.Figure` also pays a
`deepcopy` of its data in `to_dict()`. Layouts always take this path, since
they are made of components. The cost scales with the number of Python-level
values in the response: numpy arrays pass through the walk whole, lists of
floats or datetimes are visited one value at a time. 10 traces x 20k points,
Python 3.13, plotly 6.7:

| figure data | alone | + html.Div | as go.Figure | in a layout | no orjson, alone |
|--|--:|--:|--:|--:|--:|
| numpy array | 3 ms | 3 ms | 5 ms | 5 ms | 10 ms |
| list of float | 6 ms | 40 ms | 75 ms | 75 ms | 52 ms |
| pd.DatetimeIndex | 14 ms | 50 ms | 42 ms | 42 ms | 75 ms |
| list of datetime | 8 ms | 171 ms | 375 ms | 373 ms | 354 ms |

The fix belongs in plotly.py, not Dash:

- pass `default=` to `orjson.dumps` so only the non-native values are
converted, keeping the old path as a fallback on `TypeError`;
- give figures and traces a `_to_json_dict()` that skips the `deepcopy` and
copies only the containers the base64 conversion changes; skip lists of
scalars with one `set(map(type, lst))` check instead of a Python loop;
- in `PlotlyJSONEncoder.default`, return `isoformat()` first for exact
`datetime`/`date` (it now tries five encoders that raise before that one).

A local patch to plotly 6.7 doing this brought every orjson case within ~3 ms
of the figure alone (list of datetime as `go.Figure` or in a layout: 375 ->
11 ms), and the stdlib list of datetime from 354 to 109 ms. Its JSON was
identical except numpy `datetime64`, which then always uses orjson's short
form (`2024-01-01T00:00:00`), as the fast path already did.

Without orjson, what is left is the stdlib encoder: 200k floats take ~50 ms,
and 200k datetimes ~70 ms just to make their `isoformat()` strings, before
encoding. Bulk conversion does not help: numpy, pandas and pyarrow all pay
per object to read a list of datetimes (77-149 ms), and pyarrow casts a
timestamp column to strings in 5 ms but has no JSON writer for a nested
response, so the strings come back out as Python objects at the same cost.
Native encoders write bytes without Python objects: orjson and msgspec do
200k floats in ~5 ms and 200k datetimes in 2-4 ms. Making orjson a Dash
dependency is the change that helps every case.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know that this isn't new, but I question the value of the entire "Findings" section. If there is a "finding", it should be a ticket, rather than logged here where no one will see it.
In fact, it's already just become a stale log of problems that don't matter anymore.

Suggested change
dependency is the change that helps every case.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Github didn't like my giant suggestion of removing the whole section! My proposal is to delete the entire thing, not just one line.

Comment on lines +36 to +39
def test_each_click_reads_a_fresh_downlink_from_its_start():
# Installed for the load tests, not by the unit test requirements.
pytest.importorskip("aiohttp")
asyncio.run(_two_clicks())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test seems to be skipped on CI because aiohttp isn't installed there either.

Comment on lines +20 to +24
description: Run the streaming load sweep too
type: boolean
default: true
callbacks:
description: Run the HTTP vs websocket callback sweep too

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
description: Run the streaming load sweep too
type: boolean
default: true
callbacks:
description: Run the HTTP vs websocket callback sweep too
description: Run the streaming load sweep
type: boolean
default: true
callbacks:
description: Run the HTTP vs websocket callback sweep

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering about the benchmark reproducibility from run-to-run. Have you run benchmarks on CI enough to feel confident that the results won't be polluted by overloaded/slow runners?

Put another way, if a benchmark "fails", how do we know it's not a GH problem rather than a code problem?
I'm not sure what guarantees or configuration GH provides around this topic.

Comment on lines +10 to +12
# Needs "Allow GitHub Actions to create and approve pull requests" in the
# repo settings. A pull request opened with GITHUB_TOKEN starts no other
# workflows: close and reopen it to run the checks before merging.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this done? If so, we don't need this.

Suggested change
# Needs "Allow GitHub Actions to create and approve pull requests" in the
# repo settings. A pull request opened with GITHUB_TOKEN starts no other
# workflows: close and reopen it to run the checks before merging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants