The Best Sketch Depends on the Question
There is no universally best sketch. A compact cardinality estimator may excel at distinct users but cannot answer quantiles; a frequency sketch may estimate point counts but not preserve geometric clustering cost. Even two algorithms for the same statistic can trade memory, update latency, merge cost, tail error, serialization size, and resilience differently.
The familiar analogy is choosing transport. “Fastest vehicle” is incomplete without distance, cargo, roads, cost, and reliability. Likewise, “$O(1)$ update” hides constants, cache misses, vectorization, concurrency, and parameter-dependent state. Selection starts with the decision and workload, then tests candidates under the same inputs, budgets, and success criteria.
Suppose candidate A uses $8$ MB, processes $5$ million updates per second, and has p99 relative error $1.5\%$. Candidate B uses $2$ MB, processes $8$ million updates per second, and has p99 error $4\%$. If the error SLO is $2\%$, B is infeasible despite winning memory and throughput. If the SLO is $5\%$ on constrained edge devices, B may dominate.
Evidence must include ordinary and hostile conditions: skew, rare keys, changing cardinality, burstiness, deletions, merge trees, retries, saturation, incompatible states, and adaptive or malformed inputs where relevant. A benchmark is an argument about a defined population—not a property of the algorithm in every environment.
The best sketch is the least costly candidate that satisfies the full accuracy, latency, memory, merge, reliability, privacy, and operability contract for the target workload. Headline asymptotics and average error are evidence inputs, not selection decisions.
| Concept | Intuitive meaning | Exact example | Non-example or boundary | Main assumption | Question answered |
|---|---|---|---|---|---|
| Workload model | Distribution and structure of operations | Zipf keys, 90% updates, 10% queries | One convenient synthetic trace | It represents production or named stress case | What must the system handle? |
| Exact oracle | Trusted ground truth for comparison | Exact map on sampled windows | Another approximate sketch treated as truth | Oracle has validated semantics | What is the true answer? |
| Error metric | Numeric loss aligned to decisions | absolute error for small counts | Relative error when truth is zero | Edge cases and aggregation defined | How wrong is an estimate? |
| Confidence calibration | Observed failure matches claimed probability | 99% interval covers about 99% over valid trials | One lucky seed | Trials sample declared randomness/workload | Are uncertainty claims trustworthy? |
| Tail latency | High-percentile operation time | p99 update latency | Arithmetic mean alone | Measurement avoids coordinated omission | Do rare slow operations violate SLOs? |
| Throughput | Sustained completed operations per time | 8 million updates/s at fixed threads | Loop iterations without backpressure | Work and duration defined | Can capacity meet arrival rate? |
| Baseline | Reference that anchors benefit | Exact map or current production version | Deliberately unoptimized straw man | Same semantics and environment | Is approximation worth its cost? |
| Decision matrix | Constraints and trade-offs recorded together | Accuracy gate then Pareto comparison | Unexplained weighted score | Weights and vetoes are agreed | Why was this candidate selected? |
The Best Sketch Depends on the Question
Compare A: memory $8$ MB, throughput $5$ M updates/s, p99 error $1.5\%$; B: $2$ MB, $8$ M updates/s, p99 error $4\%$.
- Under error SLO $2\%$ and memory cap $16$ MB, only A is feasible.
- Under error SLO $5\%$ and memory cap $4$ MB, only B is feasible.
- Under error SLO $5\%$ and memory cap $16$ MB, neither dominates: A has lower error; B has lower memory and higher throughput.
- Add merge latency or serialization size before claiming a winner in a distributed system.
Reflection: which requirement is a hard veto, and which can be traded against cost?
Workloads, Oracles and Evaluation Metrics
An evaluation instance consists of workload $W$, candidate $A_\theta$ with parameter vector $\theta$, resource environment $E$, exact oracle $g$, and metric family $M$. Repeated trials vary input samples, algorithm seeds, machine noise, or all three—but the report must say which variation each interval represents.
For truth $y_i$ and estimate $\widehat y_i$, absolute error is $\lvert\widehat y_i-y_i\rvert$. Relative error is undefined at $y_i=0$ unless a policy is declared. Symmetric, normalized, rank, set-recall, or objective-specific loss may be better. Averages can hide tails and subgroups, so report quantiles, worst supported cases, failure rate, signed bias, and slices relevant to the decision.
Accuracy probability requires calibration. If a construction claims failure at most $\delta$, run independent trials under its theorem’s model, define failure before observing results, and estimate the rate with a confidence interval. Passing $100$ trials cannot establish a one-in-a-million guarantee.
Performance measurement separates warm-up, steady state, allocation, serialization, update, query, and merge. Report hardware, runtime, compiler, concurrency, batch size, state occupancy, memory accounting, and backpressure. Resident memory is not the same as payload bytes.
Ground truth may be computed exactly on smaller windows, sampled streams, or replayable partitions. Validate the oracle against independent implementations and include duplicate, window, weighting, and deletion semantics.
flowchart TD
A[Decision and SLOs] --> B[Formal workload model W]
A --> C[Exact oracle semantics]
A --> D[Metric definitions]
B --> E[Representative corpus]
B --> F[Stress and adversarial corpus]
C --> G[Ground-truth outputs]
D --> H[Pre-registered success criteria]
E --> I[Common trial harness]
F --> I
G --> I
H --> I
I --> J[Accuracy confidence performance resources]
J --> K[Feasibility gates]
K --> L[Pareto and risk decision]
C --> X[Failure if oracle semantics differ]
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#0D565B;
classDef crimson fill:#C6284D,color:#fff,stroke:#861B35;
classDef purple fill:#6C3BAA,color:#fff,stroke:#472675;
class A,B,C,D navy;
class E,F,G,H,I purple;
class J,K,L teal;
class X crimson;
| Metric or claim | Exact scope | Required assumptions | What it does not imply | Failure example |
|---|---|---|---|---|
| Mean absolute error | Average $\lvert\widehat y-y\rvert$ across declared cases | Cases weighted as intended | Tail or subgroup safety | Rare huge errors disappear in average |
| Relative error | Error divided by $\lvert y\rvert$ | Nonzero truth or explicit zero policy | Business impact is relative | Tiny truth creates explosive percentage |
| p99 latency | 99th percentile for measured operations | Correct sampling and load generation | Worst-case latency | Coordinated omission misses pauses |
| Throughput | Completed work per time at stated load | Backpressure and correctness enabled | Per-operation latency is acceptable | Deep queue hides slow responses |
| Empirical coverage | Fraction of truth values inside intervals | Repeated trials match claim’s randomness | Guaranteed future coverage under shift | Workload drift changes calibration |
| Payload memory | Bytes in sketch state | Serialization/layout specified | Total process memory | Allocator and indexes dominate |
| Merge cost | Time/bytes to combine compatible states | Tree, fan-in, occupancy defined | End-to-end freshness | Network and retries dominate |
An evaluation result is always conditional on its workload, oracle, parameters, environment, and randomness plan. Compare candidates only through aligned semantics and predeclared metrics; otherwise numerical differences may measure the harness rather than the algorithms.
Crossover Points, Coverage and Failure Injection
Candidate rankings often change with scale. An exact map may beat a sketch for small cardinalities because allocation and hashing constants dominate; the sketch wins after exact memory/cache costs rise. Find crossover points with parameter sweeps rather than one “large” benchmark.
Suppose measured memory is $M_E(n)=32n$ bytes for an exact map and $M_S=1{,}048{,}576$ bytes for a fixed sketch. The memory crossover solves $32n=M_S$, giving $n=32{,}768$. This says nothing about accuracy or latency, and real maps have nonlinear/cache effects, so empirical sweeps must verify the model.
Coverage studies combine dimensions: cardinality, skew, update/query mix, batch size, merge fan-in/depth, deletions, key encoding, thread count, and hardware. Full Cartesian grids may be too expensive; use designed sweeps, boundary values, risk-based pairwise combinations, and targeted adversarial cases.
Failure injection asks whether operational assumptions hold: replay batches, drop partitions, corrupt lengths/checksums, mix versions or seeds, saturate counters, force hash collisions, pause threads, reorder merges, and crash between state and provenance commits. A selection that wins only on clean inputs transfers hidden risk into production.
flowchart TD
A[Define scale dimensions and boundaries] --> B[Run exact and candidate sweeps]
B --> C[Locate accuracy resource crossovers]
C --> D[Repeat across seeds machines and merge trees]
D --> E[Check confidence calibration]
E --> F[Inject replay loss corruption saturation]
F --> G[Slice failures by workload regime]
G --> H{All hard SLOs pass}
H -->|No| X[Reject or retune]
H -->|Yes| I[Build Pareto frontier]
I --> J[Select with cost and risk priorities]
F --> Y[Repair harness if oracle or injection is invalid]
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#0D565B;
classDef crimson fill:#C6284D,color:#fff,stroke:#861B35;
classDef purple fill:#6C3BAA,color:#fff,stroke:#472675;
class A,B,C,D navy;
class E,F,G,H purple;
class I,J teal;
class X,Y crimson;
Crossover Points, Coverage and Failure Injection
An exact map uses approximately $32n$ bytes; a sketch uses $1{,}048{,}576$ bytes.
- Solve $32n=1{,}048{,}576$: $n=32{,}768$.
- Below this point, the model predicts lower payload memory for exact storage; above it, the sketch.
- Add an error gate: if the sketch’s p99 error is $3\%$ but SLO is $2\%$, it remains infeasible at every $n$.
- Measure around $n=16{,}384$, $32{,}768$, and $65{,}536$ to expose allocator/cache deviations.
- Replay a batch and mix one incompatible seed; a candidate that silently accepts either fails operational criteria.
Assumption-breaking variation: the exact map stores compact 8-byte keys rather than the assumed object overhead. The crossover changes, showing why the cost model must be measured.
| Evaluation tool | What it establishes | Assumptions | Limitation | Representative failure |
|---|---|---|---|---|
| Parameter sweep | Trends and crossover regions | Range covers deployment regimes | Sparse grid misses boundaries | Only one precision tested |
| Exact-ground-truth replay | Real-trace accuracy | Trace and oracle semantics valid | Past trace misses future shifts | No deletion traffic present |
| Seed repetitions | Randomized error distribution | Independent documented seeds | Does not cover workload uncertainty alone | One favorable default seed |
| Confidence calibration | Claimed intervals/failure rates align empirically | Enough independent trials | Rare guarantees need huge samples | 100 trials used for $10^{-6}$ claim |
| Fault injection | Behavior under operational failures | Injection mimics real failure point | Cannot enumerate every incident | Crash timing never reaches commit gap |
| Adversarial corpus | Worst-pattern sensitivity | Threat model realistic | May overfit known attacks | Collision set tailored to one hash |
| Pareto analysis | Non-dominated trade-offs | Metrics comparable and vetoes applied | Does not choose priorities | Weighted score hides SLO breach |
Selecting Under SLO, Cost and Risk
An approachable selection might compare exact counts with approximate distinct counting on a school dataset. Exact storage may be cheaper and simpler at hundreds of IDs; approximation becomes attractive only when scale, privacy, or aggregation changes.
At production scale, candidate selection includes network and operations. A sketch with smaller state but expensive merges may miss freshness SLOs. A faster design that lacks version compatibility, privacy support, or replay safety creates migration and incident risk.
Adversarial evaluation matters when keys or queries respond to outputs. A fixed-input accuracy claim does not cover adaptive chosen-key attacks. Similarly, averaging error across tenants can hide catastrophic errors for low-volume or high-value populations.
Selection should use hard feasibility gates first. Among survivors, examine the Pareto frontier. Apply monetary or weighted scoring only after metrics are normalized, uncertainty shown, and stakeholders agree on weights; document sensitivity to plausible weight changes.
Selecting Under SLO, Cost and Risk: Evaluation, Testing & Algorithm Selection
A community library expects $5{,}000$ active members. Exact set storage uses $32$ bytes/member; sketch state is $1$ MiB with $2\%$ p99 error.
- Exact payload estimate is $5{,}000\times32=160{,}000$ bytes, below $1$ MiB.
- If exact answers are required, the exact set is the feasible choice.
- If deployment grows to $100{,}000$ members, modeled exact payload becomes $3.2$ MB; the sketch saves memory if $2\%$ error is acceptable.
- Test both at $5k$, $33k$, and $100k$ with real identifiers and update/query mixes.
Success criteria: calculate crossover implications, state accuracy requirements, measure actual total memory, and document the scale at which the decision changes.
Selecting Under SLO, Cost and Risk: Evaluation, Testing & Algorithm Selection
A telemetry service processes $30$ million updates/s across $150$ regions. SLOs: p99 error below $2\%$, p99 update below $8$ microseconds, hourly global merge below $30$ seconds, memory below $2$ GB per region, and safe rolling upgrades/retries.
Plan: replay stratified production windows against an exact oracle; sweep candidate precision and seeds; measure scalar/SIMD, concurrency, serialization, and balanced-tree merges; inject skew, replay, loss, saturation, version mismatch, and chosen-key attacks; retain raw trial data and confidence intervals.
Risks: easy traces favor one candidate, tail tenants fail, benchmark hardware differs, exact oracle mishandles windows, weighted scores hide hard failures, and parameters are tuned on the final test set.
Decision: reject any SLO failure. Among survivors, select the Pareto candidate minimizing annual memory/network/CPU cost with the lowest operational risk. Validate in shadow canaries for a full window/merge cycle and predefine rollback.
Produce an Evidence-Backed Selection
A selection report should be reproducible by someone who disagrees with the conclusion. Include workload provenance and exclusions, oracle semantics, candidate versions and parameters, seed plan, environment, raw metrics, uncertainty, failure cases, feasibility gates, Pareto analysis, cost model, sensitivity analysis, canary plan, and decision owner.
Practice: Produce an Evidence-Backed Selection
Evaluate three candidates for a distinct-count service: exact map, candidate A, and candidate B.
Tier 1 — Contract. Define population, window, update/query/merge mix, supported cardinality, error SLO, latency, memory, and failure behavior.
Tier 2 — Oracle and metrics. Specify exact ground truth; define zero-safe error, bias, p95/p99 error, empirical failure, p50/p99 latency, throughput, total memory, serialized bytes, and merge cost.
Tier 3 — Experiment matrix. Sweep cardinality, skew, seeds, precision, threads, batches, merge fan-in/depth, and hardware. Mark representative, boundary, and adversarial cells.
Tier 4 — Confidence. Predefine repetitions and intervals. Explain why $100$ successful trials cannot validate $\delta=10^{-6}$.
Tier 5 — Failure injection. Test replay, missing partitions, incompatible versions/seeds, saturation, corrupt bytes, crash timing, and adversarial keys. Define expected reject/degraded behavior.
Tier 6 — Decision record. Apply hard gates, form a Pareto frontier, calculate annual cost, assess uncertainty and weight sensitivity, and write a selection, canary, rollback, and review date.
Debugging prompts: implausibly perfect accuracy suggests oracle leakage; unstable latency suggests warm-up/noise; one seed winning suggests insufficient repetitions; a winner changing with one weight suggests a fragile decision.
Stretch goal: build a sequential evaluation that stops dominated candidates early without biasing final uncertainty claims.
Rubric (10 points): workload/oracle 2; metrics/confidence 2; coverage/failures 2; fair performance methods 2; transparent decision 2.
Bridge: practical sketch engineering supplies implementation invariants; evaluation turns them into comparative evidence. The next step is continuous post-deployment validation, automatic parameter tuning, and portfolio selection as workloads drift.
Decision checklist: define the question and hard SLOs; validate the oracle; align semantics; report distributions and uncertainty; sweep scale and parameters; test tails, merges, faults, and adversaries; reject infeasible candidates before scoring; examine Pareto trade-offs and cost sensitivity; and preserve raw evidence. The benchmark winner is not the production winner unless the evaluation models production.