Skip to blog content

Experiments & observations

The blog

Things I’m building, learning, and figuring out

100 posts

Latest entry

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't
From the archive

Unlocking 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 Python
From the archive

Passive 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 signature
From the archive

Verifying 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 signatures
From the archive

Parsing 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 digits
From the archive

Parsing 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 written
From the archive

Verifying 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 rotation
From the archive

Active 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 Python
From the archive

AML 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 Python
From the archive

CDD 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 Python
From the archive

KYB 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 Python
From the archive

How 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 decision
From the archive

Measuring 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 Python
From the archive

Tool 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 bookings
From the archive

Limiting 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 order
From the archive

Stop 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.js
From the archive

Why 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 Pillow
From the archive

HNSW 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 recall
From the archive

Idempotency 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 twice
From the archive

Are 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 code
From the archive

Liveness 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 show
From the archive

Is 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 kappa
From the archive

When 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 Python
From the archive

p50 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 looks
From the archive

OCR 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 proves
From the archive

Redacting 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 numbers
From the archive

Scheduling 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 hours
From the archive

Full-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 queries
From the archive

Validating 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-Type
From the archive

Canary 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 exfiltration
From the archive

Catching 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 fraud
From the archive

Detecting 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 spaces
From the archive

Verifying 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 skew
From the archive

Limiting 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 pool
From the archive

Finding 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 RAG
From the archive

Correcting 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 guess
From the archive

Graceful 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 traffic
From the archive

Validating 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 you
From the archive

Parsing 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 bug
From the archive

Request 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 await
From the archive

Semantic 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 bug
From the archive

The 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 commits
From the archive

Idempotent 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 twice
From the archive

Fuzzy 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-Winkler
From the archive

How 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 once
From the archive

Single 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 system
From the archive

What 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 one
From the archive

My 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 interviews
From the archive

Face 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 measured
From the archive

How 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 step
From the archive

How 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 context
From the archive

Error 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 bug
From the archive

What 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 server