Scalable REST and Streaming Randomness Platform
Hard · System Design · Software Engineer · Onsite
Prompt
Architect a multi-tenant backend platform that serves random values at high throughput across both request/response HTTP endpoints and long-lived streaming channels (for instance, delivering unpredictable one-time values, unbiased bounded integers in [1, 10], or deterministic random-access batches at (stream = 3, offset = 500000) for reproducible cluster simulations and auditable selections).
Scope & Expectations
- Interfaces and versioning: Define synchronous REST and continuous streaming contracts, payload shapes, flow-control behavior, and versioning strategies for both wire schemas and generation algorithms.
- Entropy, generator classes, and reproducibility: Explain how hardware and OS entropy are harvested, justify cryptographic (
CSPRNG) versus statistical (PRNG) generator trade-offs, prevent range-mapping bias, and support deterministic seeded replay. - Tenancy, quotas, and abuse defense: Cover per-tenant rate limits and byte quotas, noisy-neighbor isolation, cryptographic hygiene, and anti-abuse safeguards.
- Operations and SLAs: Detail secret-safe observability, container rollout and horizontal scaling practices, failure modes, and target latency and availability SLAs.
Step-by-step walkthrough
Clarify scope: why call an API for random numbers?
Begin with the question every experienced interviewer asks: every modern operating system already provides fast, cryptographically strong random bytes in microseconds via a local system call (
getrandom()on Linux,secretsin Python). Why build a network service? Three real business needs justify it (especially at a regulated fintech platform running promotions, compliance audits, and risk simulations):- Cross-language, multi-year reproducibility: Monte Carlo risk simulations, A/B experiment assignments, and backtests need the exact same numbers across Python, Go, and Java workers — and again six months later during an audit. Standard library generators differ across languages and library upgrades.
- Tamper-evident audited draws: Sweepstakes, member giveaways, and regulatory compliance sampling ("select 1% of last month's wire transfers for review") require cryptographic proof of when a draw occurred, over which committed list, and that nobody secretly re-rolled until they liked the winner.
- One vetted implementation of tricky range math: Unbiased integer mapping, uniform
[0, 1)floats, andk-of-nsampling without replacement are notoriously easy to get subtly wrong across hundreds of microservices.
Explicit non-goal: Long-lived cryptographic keys (TLS private keys, database encryption keys) must never be fetched over this API because raw secret bytes would traverse network proxies and pod RAM; callers generate those locally or inside a KMS (Key Management Service) (a hardware-backed service that generates and uses encryption keys without exposing them).
Functional requirements
- Output types: raw bytes, integers in
[min, max], uniform floats in[0, 1), UUIDv4,k-of-ndistinct sample indices, and (server-seeded mode) standard normal floats. - Three operating modes:
secure: unpredictable output from a CSPRNG (cryptographically secure pseudorandom number generator), stateless, never logged or stored.seeded: deterministic, random-access sequence keyed by(algorithm_version, seed, stream, offset).audited draw: a secure or seeded draw persisted to an append-only tamper-evident ledger before returning a signed receipt.
- Transports: HTTP
POSTREST for request/response batches; gRPC and chunked HTTP streaming for continuous high-throughput consumers. - Multi-tenancy: ~300 internal services and ~20 external partner tenants with isolated quotas and blast-radius boundaries.
Non-functional requirements
- Fail closed: Never fall back to a weak generator on entropy or self-test errors — return
503 Service Unavailable. - Immutability: Once published, a versioned seeded algorithm (
blake2b-ctr@1) never alters a single output bit. - Zero output leakage: Random outputs and plaintext seeds never appear in logs, metrics, traces, or crash dumps.
- Latency & availability: Secure REST server-side p99 < 10 ms (99% of calls under 10 milliseconds) and 99.99% monthly availability (
~4.3 min/monthdowntime budget).
Back-of-the-envelope numbers
Workload assumptions Tenants ~300 internal services + ~20 external partners REST peak QPS 50,000 req/s (median payload 256 B, p99 payload 8 KiB, max 64 KiB) REST throughput 50,000 * 256 B = ~12.8 MB/s typical Concurrent streams 500 active streams; 0.2 MB/s typical, capped at 4 MB/s per stream Stream throughput 500 * 0.2 MB/s = 100 MB/s typical; 500 * 4 MB/s = 2 GB/s ceiling Audited draws 50,000/day (~0.6/s avg, bursts to 50/s when campaigns close) CPU & network sizing CSPRNG generation speed ChaCha20 / AES-CTR produces >= 1 GB/s per CPU core -> even 2 GB/s takes ~2-3 cores fleet-wide! CPU goes to TLS, auth, and JSON. REST pods per region ~5,000 req/s per pod within p99 < 10 ms -> 10 pods needed at peak; deploy 15 pods across 3 AZs (survives 1 AZ loss) in each of 2 regions Stream pods per region NIC-bound (10 Gbps NIC = ~1.25 GB/s) -> 6 pods across 3 AZs per region Durable storage Secure mode outputs 0 bytes (never persisted!) Seeded sequence metadata 100,000 active sequences * ~1 KB = ~100 MB Audited draw ledger 50,000/day * ~2 KB = ~100 MB/day = ~37 GB/year (~260 GB over 7 years)Takeaway: Storage (
< 300 GBover 7 years) and raw bit-generation CPU are tiny. The hard engineering challenges are unbiased cryptographic generation without state-cloning bugs, stateless random-access reproducibility, multi-tenant amplification defense, and 99.99% hot-path availability.API contracts and dual-axis versioning
1. Secure mode (stateless REST)
POST /v1/random/bytes {"length": 32, "encoding": "base64"} POST /v1/random/integers {"count": 5, "min": 1, "max": 10, "unique": false} POST /v1/random/floats {"count": 1000} POST /v1/random/uuids {"count": 10} POST /v1/random/sample {"population": 62500, "k": 50} 200 OK Cache-Control: no-store {"request_id": "req_4b9c...", "mode": "secure", "values": [8, 1, 10, 4, 8]} 400 INVALID_RANGE | COUNT_TOO_LARGE | UNIQUE_EXCEEDS_SPAN 429 QUOTA_EXCEEDED (Retry-After: 2) 503 GENERATOR_UNAVAILABLE2. Seeded reproducible sequences
POST /v1/sequences {"algorithm": "blake2b-ctr@1", "seed_b64": "<optional 32B>", "revealable": false, "label": "sim-q1"} 201 {"sequence_id": "seq_73d...", "algorithm": "blake2b-ctr@1", "seed_sha256": "8e1c..."} POST /v1/sequences/{sequence_id}/draw {"stream": 3, "offset": 500000, "count": 250, "type": "integers", "min": 1, "max": 10} 200 {"values": [...], "offset": 500000, "next_offset": 500250} POST /v1/sequences/{sequence_id}/reveal # Allowed ONLY when revealable=true AFTER an audited draw 200 {"seed_b64": "..."}3. Audited draws & streaming
POST /v1/draws Idempotency-Key: 91a4-3ef0... (mandatory header) {"purpose": "wire-audit-2026-q1", "type": "sample", "population": 62500, "k": 50, "source": {"mode": "seeded", "sequence_id": "seq_73d...", "stream": 0, "offset": 0, "entrants_sha256": "f02b..."}} 201 {"draw_id": "drw_...", "values": [...], "recorded_at": "2026-03-31T18:00:00Z", "receipt": {"record_hash": "...", "signature": "...", "key_id": "draw-sign-2026"}} gRPC RandomService.Stream(StreamRequest{mode, type, min, max, chunk_size, max_bytes_per_s, sequence_id?, stream?, start_offset?}) -> stream Chunk{offset, next_offset, values}Key API contract decisions: - Always
POSTwithCache-Control: no-store, neverGET: HTTPGETresponses can be cached by corporate proxies or CDNs, which would catastrophically hand identical "random" numbers to two callers. - Per-mode retry rules: Retrying asecurecall simply draws fresh values. Seeded/drawis naturally idempotent (sameoffsetalways yields the same output). Audited/drawsrequires an idempotency key (a caller token mapped to the committed ledger row) so network retries return the original draw instead of giving the caller a free re-roll. - Two independent version axes: 1. HTTP/gRPC contract version (/v1,/v2): additive fields stay in/v1; breaking schema changes ship as/v2with a 12-month overlap and RFC 8594Deprecation/Sunsetheaders. 2. Pinned algorithm version (blake2b-ctr@1): stored immutably on eachsequence_id. Even an internal optimization that flips 1 bit ships asblake2b-ctr@2so@1sequences reproduce forever.Data model and what must never be stored
tenants tenant_id PK, tier (standard | critical), allowed_modes, quotas {req_per_s, bytes_per_s, bytes_per_day, max_streams, max_batch}, status credentials credential_id PK, tenant_id, auth_type (mtls_spiffe | api_key_sha256), scopes, ip_allowlist, expires_at sequences sequence_id PK (128-bit random), tenant_id, algorithm ("blake2b-ctr@1"), wrapped_seed (encrypted via KMS envelope key), seed_sha256, revealable, created_at, expires_at draws draw_id PK, tenant_id, UNIQUE (tenant_id, idempotency_key), purpose, (append-only) request_json, source_json, values_json, recorded_at, prev_hash, record_hash, kms_receipt_sig usage_minute tenant_id, minute_bucket, endpoint, req_count, output_bytes, throttled_count- Zero persistence for
secureoutputs: Values exist only in the outgoing socket buffer. - Envelope-encrypted seeds: Anyone with a sequence's seed can predict all future draws, so
seedis encrypted via KMS (wrapped_seed) before touching PostgreSQL and never returned again (except via one-time/revealafter a commit-reveal sweepstakes draw). - Cross-region durable ledger:
tenants,credentials,sequences, anddrawslive in a small PostgreSQL cluster (primary in Region A + 1 local-AZ standby in Region A + 2 standbys in Region B, configured withsynchronous_standby_names = 'ANY 2 (...)'). Every committed audited draw lands in both regions before returning201, whilesecureREST calls never touch PostgreSQL at all.
- Zero persistence for
High-level architecture
Internal Services (mTLS) External Partners (TLS 1.3 + API Key) | | v v +----------------------------------------------------------------------------+ | Regional L7 API Gateway (Active-Active in Region A & Region B) | | - Auth + cached tenant config (30 s refresh) | | - Local token buckets (req/s, output bytes/s) + per-tenant concurrency cap | +---------------------+------------------------------------+-----------------+ | REST | gRPC / HTTP Stream v v +-------------------------------------+ +---------------------------------+ | rng-api Pods (stateless, CPU-scaled)| | rng-stream Pods (NIC-scaled) | | - Secure: OS getrandom() + unbiased | | - Per-stream ChaCha20 / PRF | | - Seeded: BLAKE2b-CTR + LRU key RAM | | - HTTP/2 window backpressure | | - Startup KAT + 1-min clone canary | | - Redis 30 s stream leases | +----+--------------+-------------+---+ +---------------+-----------------+ | | | | Linux Kernel KMS (unwrap PostgreSQL Ledger Regional Redis CSPRNG wrapped_seed (sequences + draws, (1 s batched daily (getrandom <- on cache miss) sync 2-of-3 standbys) byte quota + leases) CPU RDRAND + | virtio-rng) Daily KMS-signed hash -> WORM Object Storage Isolation: "critical" tier tenants (e.g., auth/OTP services) run in a dedicated cell (separate gateway pool + separate rng-api pods) so standard bursts never affect them.Deep dive 1: hardware entropy, cryptographic generators, and unbiased math
1. Entropy stack and CSPRNG vs. PRNG: - Entropy is physical unpredictability harvested from hardware events (CPU thermal noise via
RDRAND/RDSEED, interrupt timings, and host passthrough viavirtio-rnginside virtual machines). - A statistical PRNG (pseudorandom number generator) like Mersenne Twister (MT19937) is fast and evenly distributed, but observing just624consecutive 32-bit outputs lets an attacker reconstruct its entire internal array and predict every future number. A CSPRNG (like Linux's ChaCha20 kernel pool or NIST SP 800-90A AES-CTR DRBG) guarantees that observing gigabytes of output gives zero computational advantage in predicting the next bit. - Architectural choice: Never deploy a non-cryptographic PRNG on any security-adjacent path. Onrng-apiREST pods (~12.8 MB/sacross 15 pods,< 1 MB/sper pod), read directly from the Linux kernel CSPRNG viagetrandom()(secretsin Python): it takes< 2 microsecondsfor 256 bytes, never blocks once booted, and automatically reseeds on VM live-clone events via the hypervisor VM Generation ID. Onrng-streampods (2 GB/s), run one per-thread user-space ChaCha20 CSPRNG seeded with 32 bytes fromgetrandom(), rekeying every1 MiBor60 sand verifyingos.getpid()before each block sofork()never duplicates a stream.2. Eliminating modulo bias and float rounding bugs: - Modulo bias: If you map one random byte (
0..255,256outcomes) onto[1, 10](span = 10) via1 + (byte % 10),256 = 10 * 25 + 6, so remainders0..5appear26times while6..9appear only25times (4%relative skew!). Fix this with rejection sampling — discard values in the incomplete tail (>= 250) and redraw so every outcome1..10has exact25 / 250 = 1/10probability. - Uniform floats in[0, 1): Draw 53 random bits (matching IEEE-754 double significand precision) and multiply by2^-53. Never computeuint64 / 2^64: values near2^64 - 1round up to1.0, violating[0, 1)and breaking callers that computelog(1.0 - u)!import secrets from typing import List def secure_integers(count: int, low: int, high: int) -> List[int]: span = high - low + 1 if span <= 0: raise ValueError("high must be >= low") results: List[int] = [] for _ in range(count): # secrets.randbelow uses OS getrandom() + rejection sampling (zero modulo bias) offset = secrets.randbelow(span) results.append(low + offset) return results3. Continuous health checks & VM-clone canary (failing closed): - Startup Known-Answer Tests (KAT): Verify deterministic test vectors and a
getrandom()read before marking Kubernetes readiness healthy. - Dedicated fleet clone canary: Each pod initializes a separate in-memory canary generator fromgetrandom()at boot and emits one 128-bit canary token per minute to an internal collector (never served to users). Why separate from the serving generator? Two pods restored from the same frozen VM snapshot serve different user traffic sizes, so sampling their serving streams once a minute lands at different offsets and misses the clone! A dedicated canary steps in lockstep once a minute, immediately catching identical state. Across10^9total canary tokens (~38 years of fleet operation), accidental collision probability by the birthday bound is(10^9)^2 / 2^129 ≈ 1.5 * 10^-21— so a single match proves cloned RNG state and pages security while draining both pods (503).Deep dive 2: counter-based seeding, reproducibility, and commit-reveal
Why stateful PRNGs fail distributed reproducibility: Seeding
MT19937orPCGin memory means jumping tooffset = 500,000requires stepping forward half a million times (O(N)), parallel workers collide unless given tricky jump-ahead polynomials, and retrying a failed network chunk requires sticky server state.Solution — stateless counter-based PRF (
blake2b-ctr@1): Model the sequence as a pure mathematical functionvalue = F(key, kind, stream, index, attempt)using a PRF (pseudorandom function) — here, keyed BLAKE2b-128, available in Python'shashlib, Go, Rust, andlibsodium:import hashlib import struct TWO_64 = 2 ** 64 KIND_INT = 1 KIND_FLOAT = 2 def derive_sequence_key(seed: bytes, context: bytes = b"") -> bytes: # Derives a 32-byte PRF key; optional context mixes in entrants_sha256 for fair draws hasher = hashlib.blake2b(seed, digest_size=32, person=b"rng-seq-v1") if context: hasher.update(context) return hasher.digest() def prf_u64(key: bytes, kind: int, stream: int, index: int, attempt: int) -> int: # Pack coordinates unambiguously in big-endian: 1B kind, 4B stream, 8B index, 4B attempt coord_bytes = struct.pack(">BIQI", kind, stream, index, attempt) digest = hashlib.blake2b(coord_bytes, key=key, digest_size=16).digest() return int.from_bytes(digest[:8], byteorder="big") def seeded_int(key: bytes, stream: int, index: int, low: int, high: int) -> int: span = high - low + 1 # Supports 1 <= span <= 2**64 usable_ceiling = (TWO_64 // span) * span # Largest multiple of span <= 2**64 attempt = 0 while True: word = prf_u64(key, KIND_INT, stream, index, attempt) if word < usable_ceiling: return low + (word % span) # Retry increments attempt at the SAME index so index+1 never shifts! attempt += 1 def seeded_float(key: bytes, stream: int, index: int) -> float: word = prf_u64(key, KIND_FLOAT, stream, index, 0) # Shift right 11 bits to keep top 53 bits, then scale onto exact [0.0, 1.0) grid return (word >> 11) * (2.0 ** -53)Why this construction hits every subtle edge case: - Rejection retries never shift later offsets: Incrementing
attemptinside(kind, stream, index, attempt)keepsindex1-to-1 with output position, sooffset = 500,000is computed inO(1)time andnext_offsetis alwaysoffset + count. - Bounded worst-case loop: Rejected fraction is(2^64 mod span) / 2^64. Forspan <= 2^32, retry probability is< 2^-32; even at the adversarial worst casespan = 2^63 + 1,2^64 mod span = 2^63 - 1, so retry probability is strictly< 0.5(< 2attempts expected!). - Cross-language bit-exactness + CI golden vectors: Integers and uniform floats use only integer operations and exact power-of-two scaling (2^-53), avoidingsin/cos/logwherelibmimplementations differ in the last bit (normal@1deviates are documented as server-computed). Every SDK and CI build validates thousands of frozen golden test vectors so accidental drift fails the build immediately. - Commit-then-reveal for provably fair sweepstakes: Before entries close, the promotion team creates arevealable: truesequence with a service-generated seed and publicly postsseed_sha256. Once entries close, they run anaudited drawpassingentrants_sha256(mixed viaderive_sequence_key), and only after that draw commits indrawsdoes/revealunlockseed_b64so anyone can verifySHA256(seed) == seed_sha256and recompute the winners!Deep dive 3: byte-aware quotas, tenant bulkheads, and abuse defense
1. Byte-aware rate limiting (defending the 650x amplification vector): A tiny
100-byteJSON request asking for64 KiBof random bytes amplifies bandwidth~650x. Limiting requests/s alone is insufficient — enforce bothreq/sandoutput_bytes/s, plusbytes/dayandmax_streams: - Hot-path rates (req/s,bytes/s): Local in-memory token buckets (counters refilling atlimit / num_gatewaysper second) inside each L7 gateway pod —0 msnetwork overhead. - Daily byte quota (bytes/day): Each gateway batches tenant byte counts to regional Redis once every1 s(INCRBY quota:{tenant}:{yyyy-mm-dd} delta_bytes) and caches whether the tenant is exhausted. Worst-case overshoot acrossGgateways is at most~2 secondsof the tenant'sbytes/srate — tiny for billing/abuse protection while keeping Redis off the per-request path. - Streaming backpressure & leases:rng-streamgenerates the next64 KiBchunk only when the client's HTTP/2 or gRPC flow-control window has space, bounding per-stream RAM to~64 KiBagainst slow-loris readers. Active stream caps use a30 sRedis lease renewed every10 sso crashed pods auto-release slots.2. Multi-tenant isolation & tamper-evident audit defense: - Cell & bulkhead isolation: Critical internal tenants (e.g., login challenge nonces) route to an isolated critical cell (dedicated gateway +
rng-apipods). Within shared standard pods, per-tenant concurrency is capped at25%of worker slots, and long-lived streams live on separaterng-streampods so they never starve short REST calls. - Tenant data scoping:sequence_idanddraw_idare unguessable 128-bit IDs; querying another tenant's ID returns404 Not Found(never403, avoiding existence leaks). Core dumps are disabled (ulimit -c 0) so crash files never write unwrapped seed keys to disk. - Anti-reroll ledger integrity: Everydrawsrow computesrecord_hash = SHA256(canonical_row || prev_hash)before returning201, alerts security if one tenant submits multiple distinct idempotency keys for the samepurpose, and anchors a daily KMS-signed root hash into WORM (write-once-read-many) object storage (cloud buckets locked against deletion or modification even by root admins).Scaling, safe deployment, and per-mode SLAs
- Horizontal & multi-region scaling: Two active-active regions (
Region AandRegion B), each provisioned to carry100%of peak traffic if the other goes dark.securemode is 100% stateless;seededmode caches unwrapped 32-bytesequence_keys in pod LRU memory (10 minTTL) so> 99.9%of seeded draws avoid both PostgreSQL and KMS hops;audited drawswrite throughRegion A's primary (~50k/dayis< 1 txn/saverage, keeping the hash chain strictly linear). - Safe rollout & container hygiene: Never bake RNG state into container images or initialize user-space generators prior to
fork(). Deploy one region at a time (1 canary pod -> 5% -> 25% -> 100%), gating promotion on startup KATs, golden vectors,5xxrate, andp99latency.
Server-side SLAs (measured at regional gateway) Mode / Endpoint Latency SLA Monthly Availability ------------------------------- ----------------------------------- -------------------- Secure REST (<= 4 KiB) p50 < 2 ms, p99 < 10 ms 99.99% (~4.3 min/mo) Seeded REST (warm key cache) p50 < 3 ms, p99 < 20 ms 99.95% (~21.6 min/mo) Seeded REST (cold KMS unwrap) p99 < 60 ms 99.95% Audited draw (cross-region DB) p99 < 200 ms 99.90% (~43.2 min/mo) Streaming (gRPC / HTTP) 1st chunk p99 < 50 ms; >= 99% rate 99.95%Notice why
audited drawdeliberately carries a looser SLA (99.90%,p99 < 200 ms): it performs a synchronous cross-region PostgreSQL commit so an audited result can never be returned without being durably recorded.- Horizontal & multi-region scaling: Two active-active regions (
Failure handling, observability, and trade-off summary
Failure Scenario Caller Impact Automated System Response ------------------------------ ------------------------------ ------------------------------------------------ Pod fails KAT / RNG self-test None (retried on healthy pod) Pod returns 503, drops readiness, pages on-call Canary detects cloned RNG state None if caught on 1st minute Page security immediately, quarantine both pods KMS regional outage Cold seeded keys return 503 Warm cached keys & all secure calls unaffected PostgreSQL primary failover Audited draws 503 (~15-30 s) Promote synced standby; client retries idem_key Redis quota cluster down None Gateways enforce local rate + fallback daily cap Entire Region A outage Brief reconnect (< 10 s) Anycast shifts traffic to Region B; promote B DB- Observability without secret leakage: Track request rate,
429/503rates, latency histograms, bytes generated, rejection-sampling retry ratio (verifying it matches theoretical(2^64 mod span) / 2^64), KMS cache hit rate, and hourly offline statistical sanity suites (PractRand / NIST SP 800-22 on unserved test streams to catch buffer-plumbing regressions). Enforce a CI redaction test that injects sentinel outputs and fails the build if any byte appears in logs or OpenTelemetry spans. - Core trade-offs summarized: Direct
getrandom()over user-space caching on REST for zero fork/snapshot risk;503fail-closed over silent PRNG fallback; counter-based PRF over stateful PRNGs forO(1)random access; immutable@versionalgorithms over in-place edits; and synchronous ledger commits over availability on audited draws.
- Observability without secret leakage: Track request rate,
Intuition & how it works
Think of a network randomness platform like three specialized stations behind one secure counter — a sealed casino card shoe (secure), a numbered reference book of random tables (seeded), and a televised lottery machine with a notary public (audited draw). When an app needs an unpredictable one-time token (secure), the server pulls fresh randomness straight from the operating system's CSPRNG (cryptographically secure pseudorandom number generator) — an engine mixed from hardware entropy (physical CPU noise and interrupt timings) whose next bit cannot be predicted even after seeing gigabytes of prior output — and forgets the numbers immediately. When data scientists run a simulation across 200 workers (seeded), they look up page stream and line offset in a deterministic PRF (pseudorandom function) — a keyed cryptographic hash F(key, stream, index) that computes line 500,000 directly in one step without reading lines 0..499,999. And when a regulated audit or promotion picks winners (audited draw), the notary writes the input and result into a hash-chained ledger before handing over a signed receipt so nobody can secretly re-roll.
Why do naive designs fail? Serving random values from a fast statistical PRNG (pseudorandom number generator) like Mersenne Twister (MT19937) lets anyone who observes 624 outputs reconstruct its internal memory and predict every future draw, while exposing GET endpoints lets HTTP proxies cache and hand the exact same "random" response to multiple callers. Mapping random bytes onto [1, 10] with 1 + (byte % 10) introduces modulo bias (because 256 = 10 * 25 + 6, making 1..6 show up more often than 7..10), and stepping a stateful seeded generator forward sequentially makes random access or stateless retries impossible at scale.
Trace three concrete mini-examples showing how each subtle piece works:
1. Unbiased [1, 10] draw via rejection sampling (toy 1-byte example: 0..255 -> 1..10, span = 10):
- Largest multiple of 10 <= 256 is 250 (valid range: 0..249; remainder tail: 250..255).
- Draw byte = 253 -> >= 250 (in biased tail), REJECT and redraw!
- Draw byte = 47 -> < 250, ACCEPT: 1 + (47 % 10) = 8 (exact 25/250 = 1/10 probability each).
2. O(1) random access in seeded sequence "blake2b-ctr@1" at (stream=3, offset=500_000):
- Pod computes BLAKE2b(key, pack(kind=INT, stream=3, index=500_000, attempt=0)).
- If the 64-bit word hits the tiny rejection tail, retry with attempt=1 at the SAME index=500_000
so index=500_001 never shifts! Returns values and next_offset = 500_001.
3. Tamper-evident audited compliance draw (Idempotency-Key = "wire-audit-q1"):
- Server draws sample -> commits row + SHA256(row || prev_hash) to cross-region Postgres ->
signs receipt -> returns 201. A client retry with "wire-audit-q1" gets the exact recorded sample.
Key trade-offs
- Network RNG service vs. local OS
getrandom(). Local OS generation is faster (< 2 microseconds), has zero network outage risk, and keeps long-lived encryption keys off the wire — so encryption keys stay local or in KMS (Key Management Service). The network API exists specifically for cross-language multi-year reproducibility, notarized audited draws, and a single vetted implementation of unbiased range/sampling math. - Direct kernel
getrandom()vs. user-space DRBG on REST pods. Callinggetrandom()per REST request (~1 MB/sper pod) avoids user-spacefork()and VM-snapshot state-duplication bugs completely; per-thread user-space ChaCha20 generators (withpidchecks and frequent rekeying) are reserved for2 GB/sstreaming pods where kernel syscall throughput actually matters. - Fail closed (
503) vs. degrading to a fallback PRNG. Returning503when a startup KAT (known-answer test) or continuous health check fails costs a sliver of availability, whereas falling back to a weak generator hides the outage while silently serving predictable outputs. - Counter-based PRF (
F(key, stream, index, attempt)) vs. stateful sequential PRNG. Paying one BLAKE2b hash per coordinate buysO(1)jump-to-offset, millions of non-overlapping parallel streams, and completely stateless retries across pods, trading away a small constant factor in raw single-core CPU speed. - Immutable
@versionalgorithms vs. upgrading math in place. Freezingblake2b-ctr@1forever (enforced by CI golden test vectors) guarantees a simulation from three years ago reproduces bit-for-bit, at the cost of maintaining old algorithm code paths until every@1sequence expires. - Local gateway token buckets + 1-second Redis batching vs. synchronous central quotas. Enforcing
req/sandoutput_bytes/slocally in gateway RAM keeps hot-path latency under10 msp99 with zero Redis hop per request, trading a tiny bounded daily-quota overshoot (<= 2 sof a tenant's allowed byte rate). - Synchronous cross-region ledger write on
audited drawvs. high availability. Committing to primary + cross-region standby before returning201lowers the audited endpoint's SLA (99.90%,p99 < 200 ms) in exchange for guaranteeing a caller can never see a draw that could be lost in a regional disaster and re-rolled.
Common mistakes
- Using HTTP
GETwithoutCache-Control: no-store, allowing CDNs, browser caches, or reverse proxies to replay one random payload to multiple callers. - Modulo bias (
rand64 % span) and float1.0overflow (rand64 / 2^64), which skew non-power-of-two integer ranges and occasionally round2^64 - 1up to1.0outside[0, 1). - Using
MT19937,xorshift, orjava.util.Randomfor unpredictable tokens, letting an observer recover internal state and predict future outputs. - Initializing a user-space RNG inside a Docker image build, pre-fork master process, or VM snapshot without
pidand clone-canary checks, causing multiple containers to emit identical "random" sequences. - Advancing
indexon rejection-sampling retries in seeded mode, which makesvalue[500,000]depend on how many retries occurred in0..499,999and destroysO(1)random access! - Relying on NIST SP 800-22 or PractRand statistical suites to prove cryptographic security — statistical suites catch plumbing bugs (all-zero buffers, truncated bytes), but a predictable linear congruential or Mersenne generator passes many statistical tests while remaining insecure.
- Rate-limiting only requests/s while ignoring
output_bytes/s, leaving a650xamplification hole where tiny requests saturate NICs with64 KiBresponses. - Logging full request/response bodies in tracing middleware, leaking secret tokens and plaintext seeds into centralized log indexes.
Follow-up questions
- How can an external auditor verify that a promotional or compliance draw was not secretly re-rolled by the operator? Use a commit-then-reveal protocol combined with the hash-chained ledger: before entries close, the operator creates a
revealable: truesequence with a service-generated seed (encrypted in KMS so the operator never sees it) and publishesseed_sha256. After entries close, the operator publishesentrants_sha256(the SHA-256 of the sorted candidate list) and callsPOST /v1/drawswith bothsequence_idandentrants_sha256mixed intoderive_sequence_key, committing the result to the ledger (anchored daily to WORM write-once storage) before/revealunlocks the raw seed. Anyone can verifySHA256(seed) == seed_sha256and rerun the openblake2b-ctr@1reference script to confirm the exact same winners — and if zero trust in the platform operator itself is required, mix in the next pulse from a public randomness beacon (such as League of Entropydrand) scheduled for a timestamp after entries close. - When a quantitative team needs 100 GB of seeded floats across 200 simulation workers, should they pull from the streaming endpoint or generate locally, and why? Generate locally via the shared SDK rather than streaming over the network: pulling
100 GBover TLS at a4 MB/sper-stream quota takes nearly7 hours(100,000 MB / 4 MB/s = 25,000 s) and burns egress bandwidth to move deterministic math. Instead, the team registers onesequence_idin the service to recordseed_sha256,blake2b-ctr@1, and run metadata for auditability, while their 200 workers evaluate the local SDK onstream = 0 .. 199at> 500 MB/sper core with bit-identical results verified by shared CI golden vectors (reserving network streaming for genuinesecureCSPRNG consumers or thin clients). - Why does VM-snapshot clone detection require a dedicated canary generator rather than sampling the live serving stream, and how do you ship a new seeded algorithm without breaking older runs? Two pods restored from the same paused VM snapshot immediately serve slightly different traffic rates (say
4,200vs.3,910requests in minute one), so sampling their serving generators att = 60 scompares offset4,201against3,911and misses the clone even though3,910callers received duplicate numbers; a dedicated canary generator advances only once per minute in lockstep, colliding on tick 1. For algorithm upgrades, treat seeded engines as immutable append-only plugins keyed bysequences.algorithm: ship a faster engine under a new tag such aschacha12-ctr@2with its own frozen golden vectors, make@2the default for new sequences, and keepblake2b-ctr@1active until every@1sequence passesexpires_at.
Follow-up questions
- How can an external auditor verify that a promotional or compliance draw was not secretly re-rolled by the operator?
- When a quantitative team needs 100 GB of seeded floats across 200 simulation workers, should they pull from the streaming endpoint or generate locally, and why?
- Why does VM-snapshot clone detection require a dedicated canary generator rather than sampling the live serving stream, and how do you ship a new seeded algorithm without breaking older runs?
Similar questions
- Low-Latency Search Box Completion Platform
- Distributed Key-Value Store Using Consistent Hashing
- Stakeholder Alignment for Home-Screen Product Ranking
- Leading Through a Late-Stage Payment Roadmap Pivot
- Completed Trips from Sensor Events
- Showcasing Engineering Impact and Teaching a Technical Concept
More SoFi interview questions
- Showcasing Engineering Impact and Teaching a Technical Concept Medium
- Low-Latency Search Box Completion Platform Hard
- JVM Memory Reclamation, Singleton Trade-Offs, and SOLID Design Medium Pro
- Runner-Up Tag in Flat Triplet Records Medium Pro
- Permit-Bounded Concurrent Task Executor Medium Pro
- Reachable Vertices from a Source Node Easy Pro
- Stakeholder Alignment for Home-Screen Product Ranking Medium Pro
- Leading Through a Late-Stage Payment Roadmap Pivot Medium Pro
- Completed Trips from Sensor Events Easy Pro
- Dictionary with O(1) Latest-Entry Lookup Medium Pro