Experiments & observations
The blog
Things I’m building, learning, and figuring out
100 posts
Cosine similarity vs dot product vs Euclidean distance: when vector search results agree, and when they don't
Which similarity metric to use for vector search, tested in NumPy on 10,000 vectors: on normalised embeddings cosine, dot product and Euclidean distance return the identical top 10; on unnormalised vectors dot product shares only half of cosine's results and Euclidean only one in ten. Plus why similarity scores aren't probabilities.
Read the post : Cosine similarity vs dot product vs Euclidean distance: when vector search results agree, and when they don'tUnlocking a passport's NFC chip: deriving the BAC keys from the MRZ in Python
How a phone gets the keys to read an e-passport chip: Basic Access Control derives two 3DES keys from the document number, birth date and expiry date in the MRZ. Tested Python that reproduces ICAO's worked example byte for byte, including the mutual-authentication cryptogram, plus why one OCR misread means the chip won't answer.
Read the post : Unlocking a passport's NFC chip: deriving the BAC keys from the MRZ in PythonPassive authentication for e-passports in Python: checking data group hashes and the SOD signature
How a KYC app proves a passport chip's data is genuine: hash every data group, compare with the Document Security Object, check its messageDigest, verify the signature and chain the Document Signer certificate to the country's CSCA. Tested Python against a synthetic passport, with the forgery each check catches and the SET-vs-[0] tag bug that rejects genuine passports.
Read the post : Passive authentication for e-passports in Python: checking data group hashes and the SOD signatureVerifying Vapi webhooks in Node.js: X-Vapi-Secret, Bearer tokens and HMAC signatures
How to check that a request to your Vapi server URL really came from Vapi: the legacy X-Vapi-Secret header, Bearer token credentials, and HMAC signatures over the timestamp and body. Tested Node.js with constant-time comparison and a replay window, plus the bug that breaks every HMAC check: verifying JSON.stringify(req.body) instead of the raw bytes.
Read the post : Verifying Vapi webhooks in Node.js: X-Vapi-Secret, Bearer tokens and HMAC signaturesParsing a passport MRZ in Python: every field of TD3 passports and TD1 ID cards, with check digits
A tested Python parser for the machine-readable zone of passports (TD3, 2 lines of 44) and ID cards (TD1, 3 lines of 30): document type, issuing state, names, document number, nationality, birth date, sex, expiry, optional data and every check digit, plus what the MRZ can't tell you about names.
Read the post : Parsing a passport MRZ in Python: every field of TD3 passports and TD1 ID cards, with check digitsParsing partial JSON from a streaming LLM: show structured output while it's still being written
When an LLM streams JSON, every intermediate chunk is invalid JSON. A small tested JavaScript parser that closes open strings, drops dangling keys and half-written literals, and closes open arrays and objects, so the UI can render fields as they arrive. Every one of 119 prefixes of the test document parsed.
Read the post : Parsing partial JSON from a streaming LLM: show structured output while it's still being writtenVerifying webhook signatures in Node.js: raw body, HMAC, timestamps, replay windows and secret rotation
How to verify signed webhooks correctly in Node.js: sign over the timestamp and the raw body, compare in constant time, reject requests outside a 5-minute window to stop replays, and accept two secrets during rotation. Tested code, including why re-serialised JSON breaks the signature.
Read the post : Verifying webhook signatures in Node.js: raw body, HMAC, timestamps, replay windows and secret rotationActive vs passive liveness detection: how each works, what each stops, and a challenge-response check in Python
Active liveness asks the user to turn, blink or smile; passive liveness judges a single image or short clip without asking anything. How each works, which attacks each stops, why a random challenge only has a few dozen possible orders, and a tested Python verifier for challenge-response with nonces, timing and expiry.
Read the post : Active vs passive liveness detection: how each works, what each stops, and a challenge-response check in PythonAML vs KYC: what the difference is in practice, with a structuring-detection rule in Python
KYC checks who a customer is at onboarding; AML is the whole programme against money laundering, including monitoring what customers do afterwards. The difference explained, and a tested Python transaction-monitoring rule that flags structuring: repeated cash deposits just under a reporting threshold.
Read the post : AML vs KYC: what the difference is in practice, with a structuring-detection rule in PythonCDD vs EDD: risk-based customer due diligence, with a risk-scoring model in Python
Customer due diligence (CDD) is the standard KYC check; enhanced due diligence (EDD) adds source of funds, senior approval and closer monitoring for higher-risk customers; simplified due diligence (SDD) does less for low risk. How a risk score decides which applies, why foreign PEPs and sanctions hits override the score, and tested Python.
Read the post : CDD vs EDD: risk-based customer due diligence, with a risk-scoring model in PythonKYB vs KYC: verifying a business and finding its real owners, with a beneficial-ownership calculation in Python
KYC verifies a person; KYB verifies a business and the people behind it. How KYB works, why the 25% beneficial-ownership threshold means different things in the US and the UK and EU, and tested Python that multiplies stakes through holding companies to find owners the share register hides.
Read the post : KYB vs KYC: verifying a business and finding its real owners, with a beneficial-ownership calculation in PythonHow KYC selfie verification works: quality checks, face matching against the ID photo, and the decision
What happens when an app asks for a selfie with your ID: face detection, quality gates for size, blur and lighting, comparing face embeddings with the document photo, and turning a similarity score into match, review or retry. Tested Python for the quality gates and the decision, with the reasons a user sees.
Read the post : How KYC selfie verification works: quality checks, face matching against the ID photo, and the decisionMeasuring OCR accuracy: character error rate, word error rate and field accuracy, in Python
How to measure an OCR system properly: character error rate (CER) and word error rate (WER) from edit distance, why normalising case, spacing and digits changes the answer, and why identity documents need field-level accuracy: 2.3% CER can still mean a wrong passport number. Tested Python.
Read the post : Measuring OCR accuracy: character error rate, word error rate and field accuracy, in PythonTool calls in voice AI agents: answering within the turn, holding lines for slow tools, and retries without double bookings
A voice agent's tool call is a webhook the caller is waiting on, in silence. How to answer within a latency budget, reply with a holding line when a tool is slow and give the real result on the next turn, make retried calls idempotent by call ID, and verify the request signature. Tested Node.js.
Read the post : Tool calls in voice AI agents: answering within the turn, holding lines for slow tools, and retries without double bookingsLimiting concurrency in Python asyncio with a semaphore and per-task timeouts, in the right order
asyncio.gather over 1,000 LLM or API calls starts them all at once. How to cap concurrency with asyncio.Semaphore, give each call its own timeout, keep failures from cancelling the batch, and why putting the timeout outside the semaphore makes tasks time out without ever running. Tested Python 3.11+.
Read the post : Limiting concurrency in Python asyncio with a semaphore and per-task timeouts, in the right orderStop paying for tokens nobody reads: cancel the LLM call when the client disconnects in Node.js
When a user closes the tab mid-answer, a Node.js proxy keeps streaming the LLM response, and you pay for every token. How to abort the upstream request with AbortController when the client goes away, combine it with a timeout using AbortSignal.any, and the test that showed 5 tokens instead of 100.
Read the post : Stop paying for tokens nobody reads: cancel the LLM call when the client disconnects in Node.jsWhy your OCR sees ID photos sideways: EXIF orientation, and fixing it with Pillow
Phones store photos in the sensor's orientation and add an EXIF tag saying how to rotate them for display. OCR and face detection read raw pixels, so they see the document sideways. How to apply the orientation with Pillow's exif_transpose, and why re-encoding first loses it for good. Tested Python.
Read the post : Why your OCR sees ID photos sideways: EXIF orientation, and fixing it with PillowHNSW vs cosine similarity: one is a metric, the other is an index, and what approximate search costs in recall
Cosine similarity measures how close two vectors are; HNSW and IVF are indexes that find close vectors without comparing every one. Tested NumPy code comparing exact cosine search with an approximate index, measuring recall@10 against how much of the collection each query scans.
Read the post : HNSW vs cosine similarity: one is a metric, the other is an index, and what approximate search costs in recallIdempotency keys for POST APIs in Node.js: retry a payment without charging twice
A client retries a POST after a timeout, and the customer is charged twice. How Idempotency-Key headers work: store the first response and replay it, reject the same key with a different body, return 409 while the first request runs, and release the key on server errors. Tested Node.js with node:sqlite.
Read the post : Idempotency keys for POST APIs in Node.js: retry a payment without charging twiceAre KYC verification photos deleted? How long identity data is kept, and a retention policy in code
What happens to your selfie and ID photos after KYC: why some records must be kept for years under anti-money-laundering rules while raw images can often be deleted much sooner, and a tested Python retention policy with legal holds and abandoned applications.
Read the post : Are KYC verification photos deleted? How long identity data is kept, and a retention policy in codeLiveness detection certification explained: ISO/IEC 30107-3, APCER, BPCER and what a test report should show
What 'certified liveness' means: presentation attack detection testing under ISO/IEC 30107-3, how APCER is computed per attack type and why pooling hides weak spots, BPCER at the same threshold, and what to ask a vendor for. Tested Python for the metrics.
Read the post : Liveness detection certification explained: ISO/IEC 30107-3, APCER, BPCER and what a test report should showIs your LLM judge any good? Measuring agreement with humans using Cohen's kappa
An LLM judge that says 'pass' to everything agrees with humans 90% of the time when 90% of answers pass. Why raw agreement misleads, how Cohen's kappa corrects for chance, how to read the confusion matrix, and a quick test for position bias in pairwise judging. Tested Python.
Read the post : Is your LLM judge any good? Measuring agreement with humans using Cohen's kappaWhen a model says 95%, is it right 95% of the time? Calibration, ECE and temperature scaling in Python
A fraud or face-match model can rank cases well and still report confidence that's badly off. How to measure calibration with a reliability table and expected calibration error (ECE), and fix overconfidence with one-parameter temperature scaling. Tested NumPy code: ECE from 0.126 to 0.011.
Read the post : When a model says 95%, is it right 95% of the time? Calibration, ECE and temperature scaling in Pythonp50 vs p90 vs p99 latency explained: what each percentile tells you, and why the tail matters more than it looks
p50 is the typical request, p90 and p99 are the slow ones. A tested example where the mean describes nobody, p99 is 20 times p50, and a page that makes 20 backend calls is as slow as the per-call p90 half the time.
Read the post : p50 vs p90 vs p99 latency explained: what each percentile tells you, and why the tail matters more than it looksOCR vs NFC chip reading for passport verification: what each one actually proves
The key differences between OCR-based document verification and reading a passport's NFC chip: what each proves, what each misses, and how passive, active and chip authentication fit in. With a tested Python model of passive authentication showing an edited MRZ, a swapped photo, a forged signature and a clone.
Read the post : OCR vs NFC chip reading for passport verification: what each one actually provesRedacting personal data from logs and LLM prompts in Python: emails, CNICs, cards, IBANs and phone numbers
KYC and support systems leak personal data into logs and LLM prompts. A tested Python redactor with typed placeholders, a Luhn check so order numbers aren't mistaken for card numbers, and the phone-number pattern that redacted my test's order ID. Plus where redaction belongs and what regex can't catch.
Read the post : Redacting personal data from logs and LLM prompts in Python: emails, CNICs, cards, IBANs and phone numbersScheduling a job at 9am local time in Python: DST, skipped hours and repeated hours
A job scheduled as '9am, then every 24 hours in UTC' runs at 10am after daylight saving starts. How to compute the next local run with zoneinfo, what happens to 02:30 when clocks jump forward and to 01:30 when they fall back, and why Pakistan's fixed offset hides the bug. Tested Python.
Read the post : Scheduling a job at 9am local time in Python: DST, skipped hours and repeated hoursFull-text search with SQLite FTS5 in Python: BM25 ranking, stemming and safe queries
SQLite's FTS5 gives you BM25 keyword search with no server. How to set it up from Python's built-in sqlite3, why the default tokenizer doesn't match 'refund' to 'Refunds', why tiny indexes score everything 0, how to weight titles, and how to stop user input from breaking the query syntax. Tested code.
Read the post : Full-text search with SQLite FTS5 in Python: BM25 ranking, stemming and safe queriesValidating file uploads in Node.js: check magic bytes, not the file name or Content-Type
A file called passport.jpg with Content-Type image/jpeg can be HTML or SVG with a script inside. How to validate uploads in Node.js by their first bytes, cap the size while streaming, hash the content, and why images should still be re-encoded. Tested code for JPEG, PNG and PDF.
Read the post : Validating file uploads in Node.js: check magic bytes, not the file name or Content-TypeCanary tokens for LLM apps: detecting system prompt leaks and injected exfiltration
Put a random canary string in your system prompt and check every model output and tool call for it. How to detect leaked instructions, including spaced-out and base64 copies and leaks through tool arguments, in tested Python, and what a canary can and can't tell you.
Read the post : Canary tokens for LLM apps: detecting system prompt leaks and injected exfiltrationCatching reused ID photos with perceptual hashing: dHash in Python for KYC fraud
Fraudsters reuse the same ID card photo across many accounts, resized and recompressed. How a perceptual hash (dHash) finds near-duplicates, why you should hash the portrait instead of the whole card, and what cropping and rotation do to the distance. Tested Python with Pillow.
Read the post : Catching reused ID photos with perceptual hashing: dHash in Python for KYC fraudDetecting homoglyph names in Python: Cyrillic look-alikes, fullwidth letters and zero-width spaces
pаypal with a Cyrillic а looks identical to paypal. How to catch look-alike usernames, brand names and customer names in Python: NFKC normalisation, mixed-script detection from Unicode names, a confusables skeleton, and zero-width characters, with tests and the legitimate cases you must not block.
Read the post : Detecting homoglyph names in Python: Cyrillic look-alikes, fullwidth letters and zero-width spacesVerifying JWTs in Node.js: alg none, algorithm confusion, audience checks and clock skew
The JWT checks that get skipped and the attacks they allow: trusting the token's alg header, comparing signatures with ===, forgetting the audience, and missing exp. A small tested HS256 verifier with node:crypto that shows each check, and why production code should still use a maintained library.
Read the post : Verifying JWTs in Node.js: alg none, algorithm confusion, audience checks and clock skewLimiting concurrent async calls in Node.js without a library: a 15-line promise pool
Promise.all over 1,000 items starts 1,000 requests at once, which trips rate limits and exhausts sockets. A tested 15-line mapLimit for Node.js that caps how many run at once, keeps results in input order and doesn't let one failure stop the batch, with notes on choosing the limit for LLM and API calls.
Read the post : Limiting concurrent async calls in Node.js without a library: a 15-line promise poolRate limiting LLM API calls in Node.js: a token bucket for requests and tokens per minute
LLM APIs limit both requests per minute and tokens per minute. A client-side token-bucket limiter in Node.js that waits for both, keeps callers in order, and corrects its token estimate with real usage. Tested code with a fake clock.
Read the post : Rate limiting LLM API calls in Node.js: a token bucket for requests and tokens per minuteLuhn and IBAN check digits explained: validating card numbers and bank accounts in Python
How the Luhn algorithm validates card numbers and how IBAN's mod-97 check works, with tested Python, the one transposition Luhn can't catch, and why a valid check digit doesn't mean the account exists.
Read the post : Luhn and IBAN check digits explained: validating card numbers and bank accounts in PythonFinding near-duplicate documents with MinHash and LSH before you index them for RAG
Duplicate and near-duplicate documents waste a RAG index and crowd out diverse results. How shingles, Jaccard similarity, MinHash signatures and LSH banding find near-duplicates in pure Python, and why two versions of a policy with different numbers must not be deduplicated.
Read the post : Finding near-duplicate documents with MinHash and LSH before you index them for RAGCorrecting MRZ OCR errors with check digits: O vs 0, I vs 1, and when not to guess
OCR misreads passport MRZ characters such as O and 0, I and 1, B and 8. How to repair the document number by trying confusable swaps until the check digit matches, why a single check digit lets wrong repairs pass one time in ten, and the rule that decides between fixing and asking for a new photo. Tested Python.
Read the post : Correcting MRZ OCR errors with check digits: O vs 0, I vs 1, and when not to guessGraceful shutdown in Node.js: draining HTTP requests on SIGTERM without dropping traffic
When Kubernetes or a deploy stops a Node.js server, server.close() alone can hang on keep-alive sockets or cut requests off mid-response. The order that works: fail readiness, wait, stop accepting, close idle connections, let in-flight requests finish, then force a deadline. Tested with node:http.
Read the post : Graceful shutdown in Node.js: draining HTTP requests on SIGTERM without dropping trafficValidating a Pakistani CNIC number: the 13-digit format, what the digits mean, and what format checks can't tell you
How to validate and normalise a Pakistani CNIC number (12345-1234567-1) in Python: hyphens, Urdu digits from OCR, the region and gender digits, and why there's no check digit, so a well-formed number still needs verification.
Read the post : Validating a Pakistani CNIC number: the 13-digit format, what the digits mean, and what format checks can't tell youParsing a streamed LLM response in Node.js: Server-Sent Events, split chunks and the CRLF bug
LLM APIs stream tokens as Server-Sent Events, and network chunks don't line up with events. A tested Node.js SSE parser that handles events split mid-JSON, multi-byte characters across chunks, comments, multi-line data and a CRLF split between two chunks.
Read the post : Parsing a streamed LLM response in Node.js: Server-Sent Events, split chunks and the CRLF bugRequest IDs in Node.js logs with AsyncLocalStorage: trace one request through every await
Concurrent requests interleave their log lines. How AsyncLocalStorage attaches a request ID to every log line without passing it through each function, forwards it to downstream services, and rejects unsafe incoming IDs. Tested with 20 concurrent requests on Node.js.
Read the post : Request IDs in Node.js logs with AsyncLocalStorage: trace one request through every awaitSemantic caching for LLM apps: when reusing an answer is safe, and when it's a bug
A semantic cache reuses an LLM answer for a similar question, matched by embedding similarity. How to build one in Python, why the cache key must include the model, system prompt and tenant, how near-misses like 'cancel my order' and 'don't cancel my order' break it, and when not to cache at all.
Read the post : Semantic caching for LLM apps: when reusing an answer is safe, and when it's a bugThe transactional outbox pattern in Node.js: never lose an event when the database commits
Saving a change and publishing an event are two systems, and one can fail after the other succeeds. How the transactional outbox writes both in one database transaction, then relays events in order with retries. Tested Node.js with node:sqlite, including the ordering bug my first relay had.
Read the post : The transactional outbox pattern in Node.js: never lose an event when the database commitsHybrid search for RAG: BM25 plus vectors, merged with reciprocal rank fusion
Vector search misses invoice numbers, error codes and names. How hybrid search adds BM25 keyword retrieval and merges both rankings with reciprocal rank fusion (RRF), with tested Python and the trade-offs of k and weighting.
Read the post : Hybrid search for RAG: BM25 plus vectors, merged with reciprocal rank fusionIdempotent webhooks in Node.js: handle every event once, even when it's delivered twice
Webhook providers retry, so the same event arrives more than once. How to make a Node.js handler idempotent with a database claim on the event ID, release on failure, take over stale claims, and what 'exactly once' can and can't mean. Tested code with node:sqlite.
Read the post : Idempotent webhooks in Node.js: handle every event once, even when it's delivered twiceRetrying LLM API calls: exponential backoff, jitter, Retry-After and model fallbacks
LLM APIs return 429s, 5xx errors and overloaded responses under load. Which errors to retry, full-jitter exponential backoff, honouring Retry-After, a retry budget, and falling back to another model, with tested JavaScript.
Read the post : Retrying LLM API calls: exponential backoff, jitter, Retry-After and model fallbacksTrimming chat history to fit the context window without breaking tool calls
Long conversations outgrow the model's context window. Why keeping the last N messages breaks agents by orphaning tool results, how to trim by whole turns within a token budget, and what to do when one turn is too big. Tested Python.
Read the post : Trimming chat history to fit the context window without breaking tool callsWhich century is 74? Parsing MRZ dates of birth and expiry correctly
Passport MRZ dates have two-digit years, so 740812 could be 1974 or 2074. The rules that resolve the century for birth and expiry dates, how to compute age and expiry checks, and the cases where the visual zone has to decide. Tested Python.
Read the post : Which century is 74? Parsing MRZ dates of birth and expiry correctlyFuzzy name matching for sanctions screening: normalisation, transliteration and Jaro-Winkler
Why exact matching fails for KYC and AML name screening, and how to build a matcher that handles accents, titles, word order and Arabic transliterations such as Muhammad and Mohamed. Tested Python, plus why secondary identifiers matter more than the threshold.
Read the post : Fuzzy name matching for sanctions screening: normalisation, transliteration and Jaro-WinklerPreparing ID card photos for OCR with OpenCV: find the card, flatten it, and reject blur and glare
Most OCR errors on identity documents come from the photo, not the model. Tested OpenCV code to detect a card's corners, correct perspective to a flat ID-1 rectangle, and score sharpness and glare before OCR runs.
Read the post : Preparing ID card photos for OCR with OpenCV: find the card, flatten it, and reject blur and glareEmbeddings and vector search explained: cosine similarity, HNSW and when to add keyword search
What an embedding is, why cosine similarity measures meaning, how approximate nearest-neighbour indexes such as HNSW make search fast, and why hybrid search with BM25 beats vectors alone for names, codes and exact terms.
Read the post : Embeddings and vector search explained: cosine similarity, HNSW and when to add keyword searchHow to evaluate AI agents: task success, tool-call accuracy, cost, and running each task more than once
Agents are non-deterministic and take many steps, so one demo proves nothing. How to build an agent test set, score outcomes in code, check tool calls and trajectories, measure cost and steps, and run each task several times.
Read the post : How to evaluate AI agents: task success, tool-call accuracy, cost, and running each task more than onceKYC vs AML vs KYB vs CDD: what each means, and where AI fits in each
KYC verifies who a customer is, AML is the wider programme against money laundering, KYB verifies businesses, and CDD/EDD set how deep checks go. A plain-English guide for founders and engineers, with where automation and AI help.
Read the post : KYC vs AML vs KYB vs CDD: what each means, and where AI fits in eachHow LLM tool calling works: the loop, the schema, and the mistakes that break agents
Tool calling (function calling) lets a model ask your code to run a function. The request–execute–return loop step by step, how to write tool schemas and descriptions models use correctly, and the errors, limits and safety checks every agent needs.
Read the post : How LLM tool calling works: the loop, the schema, and the mistakes that break agentsHow NFC passport chip verification works: BAC, PACE, passive and chip authentication
E-passports carry a chip with a signed copy of the data page and photo. How a phone reads it (BAC or PACE using the MRZ), how passive authentication proves the data is genuine, and how chip authentication stops cloning.
Read the post : How NFC passport chip verification works: BAC, PACE, passive and chip authenticationRAG chunking strategies: fixed size, by heading, and what actually changes retrieval quality
How you split documents decides what RAG can retrieve. Fixed-size chunks with overlap, structure-aware chunking by heading (with tested code), keeping titles in each chunk, and how to choose sizes by measuring recall.
Read the post : RAG chunking strategies: fixed size, by heading, and what actually changes retrieval qualitySingle agent or multi-agent? What I learned building a multi-agent financial intelligence system
Multi-agent LLM systems add coordination, cost and new failure modes. When splitting work across agents helps, when one agent with good tools is better, and three design lessons from Cuttlefish: timeouts, failing closed and audit trails.
Read the post : Single agent or multi-agent? What I learned building a multi-agent financial intelligence systemWhat does an AI engineer do? A working definition, and what to look for when hiring one
An AI engineer builds products on top of models: retrieval, agents, evaluation, guardrails and the infrastructure around them. How the role differs from ML engineer and data scientist, the skills that matter, and interview questions for founders hiring one.
Read the post : What does an AI engineer do? A working definition, and what to look for when hiring oneWhat is an LLM gateway? Why teams put LiteLLM between their apps and model providers
An LLM gateway is one API in front of many model providers that adds routing, fallbacks, budgets, keys and cost tracking. What it does, when you need one, and what can go wrong, from a LiteLLM contributor.
Read the post : What is an LLM gateway? Why teams put LiteLLM between their apps and model providersA tamper-evident audit log for AI agents: three bugs in my hash chain, and the fix
Cuttlefish logs every agent action to a SHA-256 hash chain. Reviewing it, I found hashes nobody could recompute, parallel agents forking the chain, and a 'recent entries' query returning the oldest. Here's a version that verifies.
Read the post : A tamper-evident audit log for AI agents: three bugs in my hash chain, and the fixMy AI-written code detector judged Python with a JavaScript model: lessons from building one for interviews
An interview platform scored candidates' code as AI- or human-written. Reviewing it, I found every language went through the JavaScript model, line-level evidence that was manufactured, and a dataset too small to trust.
Read the post : My AI-written code detector judged Python with a JavaScript model: lessons from building one for interviewsFace liveness detection explained: presentation attacks, injection attacks and how they're measured
Liveness detection checks that a live person, not a photo, screen replay or mask, is in front of the camera. Active vs passive liveness, the ISO 30107-3 metrics APCER and BPCER, and why deepfake injection needs a separate defence.
Read the post : Face liveness detection explained: presentation attacks, injection attacks and how they're measuredFace match thresholds: how false accepts trade against false rejects in identity verification
Face verification compares two embeddings and applies a threshold. What FMR and FNMR (FAR and FRR) mean, how to choose a threshold from data with code, and why image quality, ageing and demographics move the numbers.
Read the post : Face match thresholds: how false accepts trade against false rejects in identity verificationHow KYC identity verification works: document capture, OCR, face match and liveness, step by step
What happens between 'take a photo of your ID' and 'verified': document detection, classification, OCR and MRZ checks, face matching, liveness, and the decision. An AI engineer's walkthrough of each stage and where it fails.
Read the post : How KYC identity verification works: document capture, OCR, face match and liveness, step by stepWhy you can't average p95 latencies, and how to combine percentiles correctly
Averaging per-server p95s can halve the latency you report. A worked example with real numbers, how percentile interpolation works on small samples, and the right ways to aggregate: raw samples, histograms or sketches.
Read the post : Why you can't average p95 latencies, and how to combine percentiles correctlyGetting reliable JSON from LLMs: schemas, validation, retries and a deterministic fallback
LLMs return malformed or wrong-shaped JSON more often than you'd like. How to combine provider structured outputs, Pydantic validation, a retry that feeds the error back, business-rule checks and a safe fallback, with tested Python.
Read the post : Getting reliable JSON from LLMs: schemas, validation, retries and a deterministic fallbackReal-time KYC card verification over MQTT: a pub-sub pipeline explained
A three-service KYC pipeline on MQTT: a client publishes ID card data, a verifier checks each field and publishes reasons, an analyst stores and charts results. Design choices and what QoS 1 implies.
Read the post : Real-time KYC card verification over MQTT: a pub-sub pipeline explainedWhy OCR struggles with Arabic, Urdu and other non-Latin scripts, and what helps
Connected letters with up to four shapes, Urdu's sloping Nastaliq baseline, right-to-left text with left-to-right numbers, Eastern Arabic digits, and scripts without spaces. What breaks OCR on identity documents and how pipelines handle it.
Read the post : Why OCR struggles with Arabic, Urdu and other non-Latin scripts, and what helpsHow to build a fully offline RAG chatbot with Ollama, Mistral, ChromaDB and Redis
A document Q&A chatbot for sensitive environments that needs no internet after setup: local embeddings and LLM through Ollama, ChromaDB for vectors, Redis caching, and the settings that matter.
Read the post : How to build a fully offline RAG chatbot with Ollama, Mistral, ChromaDB and RedisHow passport MRZ check digits work, with code to validate them
The two lines of chevrons on a passport are the machine-readable zone. How ICAO 9303 check digits work (weights 7, 3, 1), how to validate the document number, dates and composite digit in Python, and why OCR pipelines rely on them.
Read the post : How passport MRZ check digits work, with code to validate themPrompt injection from scraped data: guarding an LLM that writes outreach emails
LeadForge feeds Google Maps listings into an LLM that drafts cold emails. Anyone can write a listing, so it's untrusted input. The three layers I use: delimited data, output validation with a template fallback, and send gates that fail closed.
Read the post : Prompt injection from scraped data: guarding an LLM that writes outreach emailsHow to evaluate a RAG system: recall@k, MRR and groundedness, with code
Most RAG failures are retrieval failures. How to build a small golden set, measure retrieval with recall@k and MRR, check that answers are grounded in the retrieved text, and use the numbers to tune chunk size and top-k.
Read the post : How to evaluate a RAG system: recall@k, MRR and groundedness, with codeHow to cut LLM API costs without making the product worse: caching, routing, batching and context
LLM bills are mostly input tokens. The levers that work in production: measure cost per feature, trim context, prompt caching, routing easy requests to cheaper models, batch APIs for offline work, and limits on output and retries.
Read the post : How to cut LLM API costs without making the product worse: caching, routing, batching and contextError budgets and burn rates explained with code: what 14.4 means, and a maintenance-window bug
A 99.9% SLO over 30 days allows 43.2 minutes of failure. How to compute error budget spent and burn rate, why a burn rate of 14.4 over an hour pages someone, and the maintenance-window mismatch I found in my own monitoring console.
Read the post : Error budgets and burn rates explained with code: what 14.4 means, and a maintenance-window bugSecuring a voice AI agent's webhook: what my first version got right, and what I'd change
A 24/7 AI phone agent posts every call to a webhook. How HI Agent's backend verifies Vapi, stores repeated call events idempotently, and emails one summary per call, plus the fixes I'd make.
Read the post : Securing a voice AI agent's webhook: what my first version got right, and what I'd changeWhat is the Model Context Protocol (MCP)? Tools, resources, transports and auth, explained by someone who built a server
MCP is an open protocol that lets AI assistants call tools and read data from other systems. How it works (JSON-RPC, tools, resources, prompts), stdio vs Streamable HTTP, OAuth for remote servers, and what to get right when you build one.
Read the post : What is the Model Context Protocol (MCP)? Tools, resources, transports and auth, explained by someone who built a serverYour AI agent thinks its tasks were deleted: how to write tool errors for LLM agents
An agent saw 'task not found' and recreated its schedules, causing duplicates. Tool errors for LLMs must say why and what to do next. Lessons from NanoClaw and an MCP server.
Read the post : Your AI agent thinks its tasks were deleted: how to write tool errors for LLM agentsHow to see every AirPods battery on Linux, and why only one showed: LibrePods
LibrePods brings AirPods features to Linux and Android. With two AirPods connected, the Linux tray showed whichever updated last. A per-device registry fixes it, plus a smarter Android volume duck.
Read the post : How to see every AirPods battery on Linux, and why only one showed: LibrePodsFrom 10 µm to 3 nm: how chips got so small (and why 3 nm isn't 3 nm)
Intel's first microprocessor was built on a 10 µm process. Today's chips are sold as 3 nm. What shrinking transistors buys you, and what the node name really means.
Read the post : From 10 µm to 3 nm: how chips got so small (and why 3 nm isn't 3 nm)How I got my first pull request merged into LiteLLM
What my LiteLLM fix for context compression taught me about making a first open-source contribution to a large project: finding the issue, CI, and getting merged.
Read the post : How I got my first pull request merged into LiteLLMGoogle Workspace vs Zoho Mail for a small startup: is the price gap worth it?
For a 10-person team, Zoho Mail Lite cost about $120–150 a year against roughly $840 for Google Workspace. The trade-offs, and the DNS setup it took.
Read the post : Google Workspace vs Zoho Mail for a small startup: is the price gap worth it?What's inside a GPU? Cores, streaming multiprocessors and the memory problem
A GPU isn't one powerful processor. It's thousands of simple cores, specialised tensor and ray-tracing units, and a memory system built to keep them fed.
Read the post : What's inside a GPU? Cores, streaming multiprocessors and the memory problemHow can deployment platforms afford free tiers?
Servers didn't disappear. Platforms like Vercel and Render stopped renting you machines and started renting execution. Modern Deployments, part 1.
Read the post : How can deployment platforms afford free tiers?Why our AI agent looped forever: a context-compression bug in an LLM gateway
In LiteLLM, content an agent retrieved was compressed back into the same hash, so Claude Code never saw it and kept retrying. How the bug worked and how PR #38591 fixed it.
Read the post : Why our AI agent looped forever: a context-compression bug in an LLM gatewayWhy LLM cost dashboards lie when two deployments share a model name
LiteLLM's auto-router compared only provider and model, so two deployments of the same model at different prices reported $0 savings. Why identity should be the deployment.
Read the post : Why LLM cost dashboards lie when two deployments share a model nameLocalhost is not authentication: fixing a CWE-306 webhook in an AI agent framework
NanoClaw's loopback webhook accepted any local POST, letting other processes forge button clicks (CWE-306, CVSS 6.6). My fix, the maintainers' simpler one, and why theirs was better.
Read the post : Localhost is not authentication: fixing a CWE-306 webhook in an AI agent frameworkStreaming LLM output through a Next.js proxy: why you only get stream_end
Server-Sent Events through a Next.js route handler often arrive all at once or not at all. The headers, runtime flags and client parsing that make real-time LLM streaming work.
Read the post : Streaming LLM output through a Next.js proxy: why you only get stream_endWhy Node.js HTTP backpressure must count bytes, not string length
Node's OutgoingMessage counted buffered strings in UTF-16 code units, so multi-byte bodies were under-counted up to 3× and write() kept saying there was room. My fix, and how I verified it.
Read the post : Why Node.js HTTP backpressure must count bytes, not string lengthHow to build a secure MCP server with OAuth 2.1: lessons from a CRM connector
How I let Claude and other AI clients read a CRM safely: OAuth 2.1 with PKCE, single-use codes, row-level security as the only authorization, and read-only tools.
Read the post : How to build a secure MCP server with OAuth 2.1: lessons from a CRM connectorHow Rosetta, Wine and DXVK run software on machines it was never built for
Rosetta translates CPU instructions, Wine reimplements the Windows API, and DXVK turns DirectX into Vulkan. Three translation layers, three different problems.
Read the post : How Rosetta, Wine and DXVK run software on machines it was never built forWhat is a serverless cold start, really?
A cold start is the time a platform spends creating an execution environment before your handler runs. What happens step by step, and how to make it shorter.
Read the post : What is a serverless cold start, really?Your app doesn't run on a server anymore. It runs on a desired state.
Containers and orchestrators like Kubernetes mean you deploy a workload, not to a machine. What that changes, and why it matters. Modern Deployments, part 2.
Read the post : Your app doesn't run on a server anymore. It runs on a desired state.Labels vs annotations: how one YAML indent made Prometheus scrape Pyroscope twice
A Helm refactor moved prometheus.io/service-monitor from labels to annotations, so the ServiceMonitor stopped excluding Pyroscope's headless service and metrics were duplicated.
Read the post : Labels vs annotations: how one YAML indent made Prometheus scrape Pyroscope twiceHow to stop an LLM from inventing numbers: evidence containment and numeral tracing
In a research-to-LinkedIn pipeline, LLMs extract and write, but code decides what's true: verbatim evidence checks, discarding unsourced numbers, and tracing every numeral back to the paper.
Read the post : How to stop an LLM from inventing numbers: evidence containment and numeral tracingHow does Uber show cars moving in real time? A system design breakdown
Push instead of polling, H3 hexagonal indexing to find nearby drivers, and prediction plus correction to keep cars moving smoothly. How ride-hailing works at scale.
Read the post : How does Uber show cars moving in real time? A system design breakdownWhat actually gets deployed to production? (Not your code)
Production runs an immutable build artifact (a Docker image, bundle or JAR), not your repository. Why that makes rollbacks instant. Modern Deployments, part 4.
Read the post : What actually gets deployed to production? (Not your code)One phone number, two users: normalising WhatsApp sender IDs across Baileys and the Cloud API
Baileys sends 15551234567@s.whatsapp.net, the WhatsApp Cloud API sends 15551234567, so one person became two users with different roles. Canonical IDs and a merge migration fix it.
Read the post : One phone number, two users: normalising WhatsApp sender IDs across Baileys and the Cloud APIWhere do your environment variables go when you deploy?
Secrets pasted into Vercel or Render are not bundled into your build. They take a separate path and are injected at runtime, with one Next.js exception. Part 5.
Read the post : Where do your environment variables go when you deploy?How wide are London's pavements? Measuring 7,908 cross-sections in Whitechapel
No UK dataset records pavement width. I measured left pavement, road and right pavement for 10 Whitechapel streets, then tried four ways to prove myself wrong.
Read the post : How wide are London's pavements? Measuring 7,908 cross-sections in Whitechapel