London Crime Map
London Crime Map is an interactive map of every street-level crime the Metropolitan Police and City of London Police have published since December 2010: about 17 million records across 190 months, explorable in the browser by time, crime type and area. It has no backend. A Python pipeline turns the police’s bulk archives into compact binary files, a React and MapLibre app reads them directly, and a scheduled job rebuilds and redeploys the whole thing when a new month is published.
It was built spec-first with Claude Code under test-driven development.
1. A whole-city, whole-history map with no server
There’s no server, no database and no API key. The source publishes once a month, so a monthly rebuild is as fresh as any live query could be, and static files are what make a view of the whole city over the whole history feasible at all.
police.uk bulk archives --+
ONS boundaries -----------+--> Python pipeline --> binary files + meta.json --> static hosting
Nomis population ---------+ (fetch, geo, (committed to the repo) (Cloudflare Workers)
transform, emit) |
v
React + MapLibre app decodes them in the browserA visitor can see recorded crime as a density heat map, as individual points, or as a choropleth shaded by borough, ward or census small area. They can scrub or play through the 190 months on a timeline, filter by any of 15 crime categories, switch between raw counts and rates per 1,000 residents, search by postcode or area name, compare areas side by side, and open a separate stop-and-search view. The full state of any view lives in the URL, so every view can be shared.
The two halves of the project meet at one directory of data files and nowhere else. The pipeline never imports from the web app, the site never runs Python, and the only contract between them is the binary format in section 3.
2. Reading 1.6 GB archives without downloading them
Each monthly police archive is a ZIP of roughly 1.6 GB covering every force in England and Wales, and a London build wants about a fifth of one. A ZIP keeps its index at the end of the file, so the pipeline reads that index and then only the London members, using HTTP range requests. It never downloads a whole archive.
Three small reads lift one member out: the trailing 64 KB, which holds the end record and the central directory, then the member’s 30-byte local header, then the member’s own compressed bytes.
def extract(url: str, entry: ZipEntry) -> bytes:
"""The member's decompressed bytes, read straight out of the remote archive."""
header_at = entry.local_header_offset
header, _ = _get(url, header_at, header_at + _LOCAL_FIXED - 1)
if len(header) < _LOCAL_FIXED or header[:4] != _LOCAL_SIG:
raise RemoteZipError(f"no local header for {entry.name!r} at offset {header_at}")
# The local header's name and extra fields are independent of the central
# directory's, so the data offset can only be computed from the header.
name_len, extra_len = struct.unpack_from("<HH", header, 26)
data_at = header_at + _LOCAL_FIXED + name_len + extra_len
raw, _ = _get(url, data_at, data_at + entry.comp_size - 1)
if len(raw) != entry.comp_size:
raise RemoteZipError(
f"{entry.name!r}: asked for {entry.comp_size} compressed bytes, got {len(raw)}"
)
# ... inflate, then check the decompressed size against the directory'sThe whole pipeline is standard-library Python with no runtime dependencies, this ZIP reader included. Every read is bounded, so listing an archive costs the same whatever its size. The full history comes to 648 source files and about 650 MB.
3. A binary format with two independent implementations
The browser can’t parse 17 million rows of CSV, so the pipeline writes five kinds of binary file, each with a magic number and a little-endian layout: the map points, one file of crimes per month, one of stop-and-search per month, a cube of borough totals, and population by year. A JSON manifest is the decoding key that says what the indices mean.
Coordinates are delta-encoded at a precision of a millionth of a degree, and points are sorted by quadkey so that neighbors sit next to each other. Blocks are padded to 4-byte boundaries, because the browser builds typed-array views straight over the downloaded buffer and a misaligned view throws.
// Running totals in whole micro-degrees: exact in a float64, and only
// divided down once per point so no rounding accumulates along the run.
let latMicro = latOrigin;
let lngMicro = lngOrigin;
for (let i = 0; i < count; i++) {
latMicro += dv.getInt32(latOff + 4 * i, true);
lngMicro += dv.getInt32(lngOff + 4 * i, true);
lat[i] = latMicro / 1e6;
lng[i] = lngMicro / 1e6;
}
return {
count,
lat,
lng,
lsoa: new Uint16Array(buf, POINTS_HEADER + 8 * count, count),
ward: new Uint16Array(buf, POINTS_HEADER + 10 * count, count),
borough: new Uint8Array(buf, POINTS_HEADER + 12 * count, count),
};The rule that matters most is that the Python encoder and the TypeScript decoder were each written from the written specification and never from each other. They’re bound together by shared fixture files. A decoder written alongside its encoder inherits the encoder’s mistakes, and then the fixtures test nothing but self-consistency.
That independence paid off twice. When the decoder was first written, every fixture assertion passed on the first run without the encoder’s source being opened. Later the decoder contradicted the encoder’s own docstring about alignment, and the decoder was the one that was right.
Round-trip tests don’t replace it. Encoding and then decoding proves that the two sides agree with each other, and nothing about whether either matches the specification: a category order permuted consistently on both sides passes every round trip while every crime lands in the wrong channel. So the encoder’s tests read the output at byte offsets computed by hand from the specification.
4. Data quality gates
The pipeline’s output is a valid binary file whether the input was right or not. A truncated download and a renamed crime category both produce a file that decodes cleanly and looks exactly like crime having fallen. Two gates stand between that and a published map.
An anomaly gate. Every month and category is compared with the median of its six neighbors, and a deviation beyond 50% fails the build unless a reviewed baseline entry accounts for it. The baseline is a regression baseline and not suppression: a month is judged against its neighbors forever, so a real anomaly never ages out. Each accepted entry records why it was accepted, and where the cause is unknown it says so instead of inventing one.
A coverage gate. A build is refused if the series has a gap, or if it would drop a month that’s already published:
built = set(months)
span = expected_months(config.FIRST_MONTH, max(built)) if built else []
return Coverage(
holes=tuple(month for month in span if month not in built),
dropped=tuple(sorted(_listed_months(published, "months") - built)),
dropped_stops=tuple(
sorted(_listed_months(published, "stopMonths") - set(stop_months))
),
)The police also restate months they’ve already published, with no signal that anything changed. Every rebuild is diffed against the manifest that was live before it, and the report says which months moved and by how much, because a silent restatement and a bug in the pipeline look identical from the outside.
Geography needed its own care. Records from before 2021 use 2011 census areas, and the pipeline bridges them to 2021 areas with the official change indicators. Merges are resolved exactly. Splits are deliberately left unresolved, because resolving them would mean guessing.
The app is equally plain about what the data can’t say. It discloses the records that can’t be mapped, draws gaps instead of zeros where a category didn’t exist yet, shows flagged months with their reviewed explanation, and never implies address-level precision. Police locations are anonymized to a fixed set of map points, which is why 17 million records fall on about 152,000 of them.
5. The incident: three one-month builds
The coverage gate exists because of the worst thing that happened to this project. On three scheduled runs, in September, October and November 2026, the job built and committed a site containing exactly one month. 324 data files and 187 months became 8 files and one month.
The cause was an incremental mode that narrowed the download to the newly published month and then rebuilt “everything”, where everything meant whatever the runner’s cache held. On a runner whose cache had been evicted, that was one month.
Nothing failed, and that’s the part worth keeping:
- The anomaly gate measures a month against its neighbors. A month with no neighbors deviates from nothing, so it passed.
- The restatement report printed “1 added, 187 removed” on the first run, and it’s informational by design. On the next two runs it printed “1 added, 1 removed”, which reads as routine.
- The test workflow never ran on the result, because a push made with a workflow’s own token doesn’t start another workflow. No commit the job made was tested before it would have deployed.
None of the three builds reached the public, and only because the deploy step had no hosting credentials at the time. That was luck and not design.
It was diagnosed from the CI logs, the three commits were reverted, and the cause was fixed: a scheduled run now rebuilds from the source archives, and the coverage gate refuses any build that isn’t the whole series. The failure is covered by tests that reproduce it, and it’s written up in the project’s deployment notes.
6. Seventeen million records in the browser
The app never holds the whole dataset. Borough totals for every month come from one small pre-aggregated cube, a month’s points are fetched only when that month is shown, and the next months are prefetched during playback. A Web Worker decodes each file into typed arrays off the main thread. The first page load is 2.79 MB.
Three map modes sit on that one data model: a kernel-density heat layer whose scale is calibrated per crime type across the whole history, a points layer, and choropleths at three area levels. The charts are hand-built SVG, with no charting library.
TypeScript runs in strict mode with unchecked index access and exact optional properties turned on, split into four projects so that browser code can’t accidentally use Node APIs. Accessibility is a build gate: axe-core runs in the end-to-end suite on both the desktop and the phone layout, and keyboard operation, target sizes and text contrast are tested.
One thing is still open. The binary files are served uncompressed on the current hostname. A compression rule would cut the first load to roughly 0.8 MB, but it needs a custom domain, which the site doesn’t have yet. The performance tests keep the budget measured in the meantime.
7. Tests and reproducible builds
| Suite | Tests |
|---|---|
| Pipeline (pytest) | 529 |
| Web unit (Vitest) | 832 across 39 files |
| End to end (Playwright, against a production build with the real data) | 49 |
The source is about 6,600 lines of Python and 16,500 of TypeScript, with roughly 17,500 lines of tests across the three suites.
Two properties of the tests matter more than their number. The end-to-end tests read their expectations from the build under test, so a monthly data refresh can’t break the suite. And the builds are reproducible: a rebuild on a CI runner under Python 3.11 produced output byte-identical to a local build under Python 3.14, in every file except the build timestamp.
A scheduled workflow checks for a new month four times a month, because the police have no fixed publication day. When one appears, it rebuilds from source, runs the gates, commits the data and deploys. A full rebuild on a hosted runner takes about 17 minutes.