Back to Streaming Sketching

Evaluation, Testing & Algorithm Selection

September 27, 2026 Wasil Zafar 18 min read

Select algorithms with evidence rather than headline complexity.

Table of Contents

  1. The Best Sketch Depends on the Question
  2. Workloads, Oracles and Evaluation Metrics
  3. Crossover Points, Coverage and Failure Injection
  4. Selecting Under SLO, Cost and Risk
  5. Produce an Evidence-Backed Selection

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.

From operational question to evidence-backed sketch selection A decision and workload define constraints; candidates are evaluated and filtered before a trade-off choice. Questionstatistic • decisionsworkload • SLOsrisk • budget Common experiment exact oracle + fixed seedsaccuracy + confidencelatency + memory + merge fault/adversarial cases Decision reject SLO fails feasible set Pareto frontierchoose by declared priorities Selection is conditional on the question; changed constraints can change the winner.
ConceptIntuitive meaningExact exampleNon-example or boundaryMain assumptionQuestion answered
Workload modelDistribution and structure of operationsZipf keys, 90% updates, 10% queriesOne convenient synthetic traceIt represents production or named stress caseWhat must the system handle?
Exact oracleTrusted ground truth for comparisonExact map on sampled windowsAnother approximate sketch treated as truthOracle has validated semanticsWhat is the true answer?
Error metricNumeric loss aligned to decisionsabsolute error for small countsRelative error when truth is zeroEdge cases and aggregation definedHow wrong is an estimate?
Confidence calibrationObserved failure matches claimed probability99% interval covers about 99% over valid trialsOne lucky seedTrials sample declared randomness/workloadAre uncertainty claims trustworthy?
Tail latencyHigh-percentile operation timep99 update latencyArithmetic mean aloneMeasurement avoids coordinated omissionDo rare slow operations violate SLOs?
ThroughputSustained completed operations per time8 million updates/s at fixed threadsLoop iterations without backpressureWork and duration definedCan capacity meet arrival rate?
BaselineReference that anchors benefitExact map or current production versionDeliberately unoptimized straw manSame semantics and environmentIs approximation worth its cost?
Decision matrixConstraints and trade-offs recorded togetherAccuracy gate then Pareto comparisonUnexplained weighted scoreWeights and vetoes are agreedWhy was this candidate selected?
Warm-up

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\%$.

  1. Under error SLO $2\%$ and memory cap $16$ MB, only A is feasible.
  2. Under error SLO $5\%$ and memory cap $4$ MB, only B is feasible.
  3. Under error SLO $5\%$ and memory cap $16$ MB, neither dominates: A has lower error; B has lower memory and higher throughput.
  4. 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.

Evaluation, Testing & Algorithm Selection: Workloads, Oracles and Evaluation Metrics
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;
Formal evaluation model Workload, candidate parameters, environment, and exact oracle feed a common harness that produces accuracy, confidence, and cost evidence. Workload W Candidate Aθ Environment E Exact oracle g Common harnessseed plan • repetitions • warm-upfault injection • exact comparisonraw results retained Evidenceerror distribution + biascoverage + failure ratep50/p99 latencythroughput • memory • merge slices + failures Raw evidence is conditional on W, θ, E, oracle semantics, and trial randomness.
Metric or claimExact scopeRequired assumptionsWhat it does not implyFailure example
Mean absolute errorAverage $\lvert\widehat y-y\rvert$ across declared casesCases weighted as intendedTail or subgroup safetyRare huge errors disappear in average
Relative errorError divided by $\lvert y\rvert$Nonzero truth or explicit zero policyBusiness impact is relativeTiny truth creates explosive percentage
p99 latency99th percentile for measured operationsCorrect sampling and load generationWorst-case latencyCoordinated omission misses pauses
ThroughputCompleted work per time at stated loadBackpressure and correctness enabledPer-operation latency is acceptableDeep queue hides slow responses
Empirical coverageFraction of truth values inside intervalsRepeated trials match claim’s randomnessGuaranteed future coverage under shiftWorkload drift changes calibration
Payload memoryBytes in sketch stateSerialization/layout specifiedTotal process memoryAllocator and indexes dominate
Merge costTime/bytes to combine compatible statesTree, fan-in, occupancy definedEnd-to-end freshnessNetwork 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.

Memory crossover between exact and fixed-size sketch state Exact memory grows linearly with cardinality while sketch memory remains fixed; an accuracy gate remains separate. distinct count nmemory bytes exact: 32n sketch: 1 MiB n = 32,768 Sketch feasible only if accuracy SLO also passes Validate model with measured cache/allocator effects
Evaluation, Testing & Algorithm Selection: Crossover Points, Coverage and Failure Injection
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;
Worked Derivation

Crossover Points, Coverage and Failure Injection

An exact map uses approximately $32n$ bytes; a sketch uses $1{,}048{,}576$ bytes.

  1. Solve $32n=1{,}048{,}576$: $n=32{,}768$.
  2. Below this point, the model predicts lower payload memory for exact storage; above it, the sketch.
  3. Add an error gate: if the sketch’s p99 error is $3\%$ but SLO is $2\%$, it remains infeasible at every $n$.
  4. Measure around $n=16{,}384$, $32{,}768$, and $65{,}536$ to expose allocator/cache deviations.
  5. 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 toolWhat it establishesAssumptionsLimitationRepresentative failure
Parameter sweepTrends and crossover regionsRange covers deployment regimesSparse grid misses boundariesOnly one precision tested
Exact-ground-truth replayReal-trace accuracyTrace and oracle semantics validPast trace misses future shiftsNo deletion traffic present
Seed repetitionsRandomized error distributionIndependent documented seedsDoes not cover workload uncertainty aloneOne favorable default seed
Confidence calibrationClaimed intervals/failure rates align empiricallyEnough independent trialsRare guarantees need huge samples100 trials used for $10^{-6}$ claim
Fault injectionBehavior under operational failuresInjection mimics real failure pointCannot enumerate every incidentCrash timing never reaches commit gap
Adversarial corpusWorst-pattern sensitivityThreat model realisticMay overfit known attacksCollision set tailored to one hash
Pareto analysisNon-dominated trade-offsMetrics comparable and vetoes appliedDoes not choose prioritiesWeighted 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.

Evidence-driven selection in a production pipeline Representative and adversarial workloads feed an exact oracle and candidates, with SLO gates and a risk-aware decision. Production replayslices • bursts • merges Stress/adversarialreplay • skew • corruption Evaluation harnessexact oraclecandidate matrixresource measurementsconfidence + risk evidence reproducible record SLO gateaccuracylatency/memorymerge/faultsprivacy/operability Selectcanaryreview Trust boundary: oracle, workload provenance, and raw results remain auditable.
Case Study

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.

  1. Exact payload estimate is $5{,}000\times32=160{,}000$ bytes, below $1$ MiB.
  2. If exact answers are required, the exact set is the feasible choice.
  3. If deployment grows to $100{,}000$ members, modeled exact payload becomes $3.2$ MB; the sketch saves memory if $2\%$ error is acceptable.
  4. 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.

Production

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

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.