ayoub chahid

Regish, under the hood

How Regish works: where the data comes from, how it's stored and cleaned, how a search over 53 million plates answers in a fraction of a second on a Raspberry Pi, and how it keeps itself up to date.

Every number here comes from my own runs. Back to the Regish story.

The stack

I kept it small on purpose: one language for the data and the server, one database file, and no JavaScript framework or build step.

PartWhat I usedWhy
DataDVSA MOT History API: a weekly bulk file plus daily changesFree, and it includes the model, which the DVLA's API doesn't
StorageSQLiteOne file, no server process, and very fast reads for data that is mostly read
Searchnumpy arrays held in memoryAny pattern, exact counts, a fraction of a second
WebsiteFastAPI, Jinja templates, a JSON API, plain JavaScriptThe same Python as the data code, and light enough for a Pi
ServerRaspberry Pi 4 (8 GB) with a 1 TB SATA SSDFree to run, and already in my drawer
Public accessCloudflare TunnelHTTPS, no open ports at home, home IP hidden
Updates and alertssystemd timers, healthchecks.io, UptimeRobotRuns without me, and emails me when something stops

Cutting down the plates before calling the API

Before the bulk data, every search meant generating every possible plate and looking each one up. UK plates follow a handful of formats, and each position only allows certain characters, so I wrote the format rules first to avoid wasting lookups on plates that can't exist.

The formats the generator knows
FormatShapeIn use
Current2 letters, 2 digits, 3 letters (DA11 ABZ)2001 onwards
Prefix1 letter, 1 to 3 digits, 3 letters (A123 BCD)1983 to 2001
Suffix3 letters, 1 to 3 digits, 1 letter (ABC 123D)1963 to 1983
Dateless1 to 3 letters and 1 to 4 digits, either way roundBefore 1963
Northern Ireland3 letters, 4 digitsStill issued
What the rules save on DA11 _ _ _ (the last three letters never use I or Q)
ApproachCharacters per positionPlates to look upAt 600 a minute
Every letter and digit3646,65678 min
With the format rules2413,82423 min

Finding the real rate limit

The DVLA doesn't publish its rate limit, so I measured it: hold one request rate for 60 seconds, count how many requests come back as HTTP 429 (too many requests), then step up.

Requests a secondPer minuteRefused
106000%
1272017%

Why not just go faster

By then the limit was the API, not my code. The script settled on 9 requests a second, shared between 5 worker threads through one token bucket, so together they stay just under the limit. I'd also written an async version with aiohttp, but more concurrency doesn't help when the bottleneck is the other side's rate limit. The DVLA confirmed by email that there's no batch endpoint, and that higher limits need a business case. That's when I went looking for bulk data.

Loading 53.4 GB of JSON into SQLite

The DVSA's weekly bulk file is a zip of about 470 gzipped JSON parts. Each record has the registration, make, model, colours, fuel, engine size, several dates, and the vehicle's whole MOT test history.

  • Streamed, never unpacked. The loader reads each part straight out of the zip and through gzip into SQLite. Unpacking first would need many times 53 GB of disk and an extra pass.
  • Resumable. It commits after every part and records it in a loaded_files table, so an interruption only loses the part it was on.
  • Only the latest MOT. Storing every test with every defect would take hundreds of GB. A search only needs the latest result and expiry.
  • A reversed registration column. SQLite can only use an index for the known start of a GLOB pattern. Storing each plate backwards, with its own index, makes "end of the plate known" searches indexed too.
FileSizeVehicles
Weekly bulk zip53.4 GBevery vehicle with an MOT since 2005
mot.db, after loading it20.3 GB138,539,073
One daily change file110 to 130 MBthe vehicles that changed that day

From 138.5 million rows to the website's database

mot.db holds every vehicle that ever had an MOT, inserted in random order, so any pass over it costs about 27 minutes. I split building the website's database into three stages so that changing a cleaning rule doesn't mean another full pass.

StageWhat it doesTime
ExtractReads mot.db once and writes only the vehicles to keep into raw.db, in registration order, in 37 chunks by first character26 min
TransformApplies the cleaning rules and writes web.db.new, which replaces web.db only when it's finished10 min
IndexBuilds the search indexes2 min
Which vehicles are kept
RuleVehicles
Every vehicle in the MOT data138,539,073
MOT expired in the last 5 years, or registered in the last 5 years53,440,814
Plus classics over 40 years old whose last MOT ran out from 2015 (2010 if built before 1960)+439,553
Total after the 14 Nov rebuild53,880,367

Cleaning, by the numbers

I explored all 53 million kept vehicles before writing any rule, so the rules come from the real values rather than guesses.

FieldRaw valuesAfter cleaningWhat happens
Make17,292 spellings16,997 (692 with 50+ vehicles go in the dropdown)Case and spacing merged; Smart (MCC) and Smart, London Taxis Int and LEVC; about 80 hand-picked typos like Volkswagon and Citreon
Primary colour41 values19 coloursWhite (10,259,210) and WHITE (285,625) are one colour; UNKNOWN and Not Stated become blank
Fuel14 values6 groupsHybrid Electric (Clean) and Electric Diesel become hybrid; LPG, CNG, LNG and Bi-Fuel become gas
YearSome impossible, like 4 and 1006Rejected

Models were the hard part

  • Mercedes models are often just "C" or "E".
  • MINI models are named after trims (Cooper, One, John Cooper Works) rather than bodies.
  • Land Rover appears as R ROVER, RROVER and RR.
  • Electric versions (E-208, VIVARO-E) are grouped with their usual model.
  • Names that differ only by spaces, dots or hyphens (B M W, Can Am) are merged, but real lookalikes stay apart: Ducato, Alpina and Leeway are not typos.

I chose rules over a hand-written table of every model: that would be thousands of entries for little gain. The rules cover the common cases, and the rare oddities only show up as small extra entries in a dropdown.

Search, version one: SQL indexes

The first search engine was plain SQLite. When two or more characters were known at either end, it ran range scans on the registration or on the reversed registration. Lookalike characters (0 and O, 8 and B) became at most 16 ranges. Otherwise it used the make or colour index, and with nothing to go on it answered "too broad" without running a query.

Up to 20,000 matches were fetched once, and the filters, the counts for every option, sorting and paging then happened in Python. Each option's count ignores its own filter, so the colour list still shows what the other colours would give. A 3 second budget stops any query that runs too long.

The Pi's first lesson: cold reads

On my PC the median search took 0.05 s. On the Pi, searches by the end of the plate, by make or by colour took up to 3 seconds. Plates sharing an end, a make or a colour are scattered across a 10 GB table, and the Pi only has 8 GB of memory, so most reads were random reads from the SSD over USB.

The fix was covering indexes: indexes on the reversed plate, on make, model family and year, and on colour and year, each holding every column a search needs. A search then reads one continuous run of index pages, and only reads the full rows for the 50 vehicles on screen. It cost 8.4 GB of disk (10.55 GB to 18.96 GB).

On the Pi, first run of each search
SearchPatternBeforeAfter
Start knownDA11___0.233 s0.206 s
End known____KBZ2.792 s0.225 s
Ends with XYZXYZ2.549 s0.223 s
Nothing typed, BMW 3 Series, black, 2011_______3.119 s0.542 s
One end character, Ford Focus______Zover 3 s0.560 s
Nothing typed, pink_______3.037 s0.259 s

Search, version two: an in-memory grid

Indexes only help when you know the start or the end of a plate. A gap at both ends, like _A10___, had to be refused as too broad, and counts stopped at "20,000+". So I replaced the plate indexes with a grid of numpy arrays that the server keeps in memory.

What's in the grid: 53,403,443 plates of up to 7 characters
ColumnsStored as
One column per plate position (7)uint8, one byte per character
Make, model family, colour, fuel, plate styleSmall integer codes
Year, engine size, MOT expiry, first registrationSmall numbers
An end-aligned copy of the charactersuint8, +350 MB, built on first use

How a search runs on the grid

  • The grid is sorted by plate, so a known start (DA10) is one block of rows, found by binary search.
  • The other known positions narrow the candidates one at a time, so only one full column is ever scanned.
  • "Ends with" searches use the end-aligned copy, which makes them as cheap as "starts with".
  • Filters are boolean masks, and np.bincount counts every make, colour and year option exactly in one pass.
  • SQLite is read only for the 50 rows on the page.
  • One gotcha: comparing a uint8 column with a plain Python int makes numpy copy all 53 million rows to compare them. Comparing with np.uint8 instead took one step from 170 ms to 0.1 ms.
  • Plates longer than 7 characters (about 17,500 odd foreign and trade plates) are left out, since the site's input stops at 7. Over 93% of plates are exactly 7 characters.
The grid file
Value
Size on disk (web.grid.npz)1.39 GB
Load time, PC0.8 s
Load time, Piabout 6 s
Rebuild after an update, PC252 s
On the Pi, before and after tuning the grid
First Pi runAfter tuning
Median search0.75 s0.22 s
Ends with (ABZ)3.5 s0.21 s
Filter only, nothing typed3 to 5 sAsks for at least one character
Searches on the Pi now
PatternMatchesTime
DA10___0.001 s
D_1___Z with BMW0.05 s
_A10___ (refused by version one)49,2630.23 s
__10___0.95 s
___1___4,362,1301.16 s

Keeping 53.9 million vehicles up to date

The DVSA publishes a change file every day: complete records marked CREATED, UPDATED or DELETED. A timer on the Pi runs the updater at 09:30, 15:30 and 21:30. (systemd's OnCalendar wants that written as 09,15,21:30:00; my first version, a list of times, was quietly wrong.)

The catch is that the API only lists the change files since its latest weekly bulk file. If the Pi misses a few days at the wrong moment, those days disappear for good. So the updater compares the newest file it has applied with the oldest one the API lists, and if a day might be missing it rebuilds the whole database from the weekly bulk instead of carrying on with a hole in the data. The old database keeps serving searches until the new one replaces it with a single rename, then the grid is rebuilt and the site restarts.

The first automatic rebuild on the Pi, 12 Nov
StepTimeDetail
Download the bulk zip28 min53 GB, about 34 MB/s
Stage209 min138,625,779 records read, 53,438,037 kept, about 11,050 a second on one core
Build11 min
Apply 4 daily files7 min
Index and ANALYZE18 min
Total4.6 hThe Pi hit its soft temperature limit, with no under-voltage
What tells me something's wrong
CheckHow oftenCatches
Pi heartbeat (healthchecks.io)Every 5 min, 10 min gracePower cut, crash, lost network
Data update (healthchecks.io)Every 12 h, 18 h graceAn update that failed or didn't run
Website (healthchecks.io)With the heartbeat, after checking /healthzThe app down while the Pi is up
UptimeRobotFrom outsideThe site unreachable from the internet

Why the alerts come from outside

A server can't report its own power cut. So the Pi sends pings, and outside services email me when the pings stop.

The server

Everything, the data included, runs on one Raspberry Pi at home. Using 25 GB of its 917 GB after a rebuild, it has plenty of room.

PartDetail
BoardRaspberry Pi 4 Model B, 8 GB
StorageSamsung 860 QVO 1 TB on a SupTronics X825 SATA shield, USB 3 in UAS mode, 341 MB/s
SystemRaspberry Pi OS Lite 64-bit (Debian 13), Python 3.13
NetworkEthernet only, reserved address on the router, Wi-Fi off
Public accessCloudflare Tunnel: outbound only, no ports open at home
LoginsSSH keys only, no root login, firewall allows SSH from the home network only, automatic security updates
The appIts own system user, its folder readable only by that user, secrets in a separate file, a systemd service on 127.0.0.1

Problems I hit setting it up

  • The first SSD. The kit came with a Crucial M4 whose firmware has a known bug that freezes it after 5,184 hours of use. It had 5,821. The firmware updater needed legacy boot, which my PC doesn't use, so I moved the Pi to a Samsung 860 QVO instead. A spare hard drive was ruled out: random reads would push broad searches past 3 seconds.
  • Imager wouldn't write the SSD. It said the disk still had partitions after wiping it. I traced it to Google Drive for desktop: its virtual drives answer Windows' device-number query with 0, the same number as the SSD, so Imager thought it had found partitions. I confirmed it by making the same calls from PowerShell. Quitting Google Drive fixed it.
  • TRIM. The SATA bridge didn't pass TRIM through. The bridge chip (ASMedia 174c:0825) does support UNMAP, so a udev rule setting provisioning_mode=unmap fixed it, and the first run trimmed 891.8 GiB.
  • Launch day. The site wouldn't start on the Pi because a systemd setting made the data folder read-only, and SQLite needs to create a small shared-memory file even when only reading. Fixed the same day.

The web app

FastAPI draws the page frame with Jinja, and the search page asks a JSON API for results and draws them with plain JavaScript. I'd planned server-drawn results with htmx, but the plate input, the filter pop-up with live counts and the quiet search while typing were all in JavaScript already. Typing fires a search in the background, and its answer is kept until you press Search, so results appear instantly.

RouteWhat it does
/api/searchResults as JSON, 50 a page, with exact counts for every filter option
/api/modelsThe models for one make
/export.csvUp to 5,000 rows as a spreadsheet
/vehicle/{reg}One vehicle's facts, kept out of search engines
/healthzData date, vehicle count, and whether the grid is loaded

Keeping it safe and light

  • One worker process. The grid is 1.4 GB, so a second worker would need a second copy. The database is opened read-only, with one connection behind a lock.
  • Rate limits per visitor, keyed on Cloudflare's CF-Connecting-IP header: 60 searches a minute and 10 spreadsheets an hour. Paging stops at page 200 (10,000 vehicles), so nobody can page through the whole database.
  • A strict content security policy with no inline scripts, plus nosniff, a referrer policy and a permissions policy. No API docs pages in production.
  • Privacy. No cookies. Visitor counting with GoatCounter records the page type, never the plate.

What I'd do next

  • Spread the rebuild's stage step across the Pi's four cores. It runs on one at about 11,000 records a second, which is the bulk of the 4.6 hours.
  • Show a vehicle's full MOT history live on its page, from the single-vehicle MOT endpoint.
  • Read a plate straight from a photo.

Back to the Regish story, or try it at regish.co.uk.