A Privacy Perserving Postcode Lookup Tool
Published: 2025-06-27 Updated: 2026-01-13
This blog post is also available as a video series! Watch it on
YouTube: Part 1 | Part 2 | Part 3
Part of a series of posts: Next in series >
Let’s talk about store locators.
You’ve probably used a website that has a store locator. For example, there’s a chain of supermarkets in the UK called The Coop. On their website is a store locator. You can type in a postcode and it will list a selection of your closest Coop shops.

If you have a look at the network tab in the developer tools when you use it, you will see that the postcode is sent to some web server. Before I’ve even typed the whole thing it’s made an API request to get a list of possible postcodes that I might be interested in. When I select a postcode from the list, it then sends that to a different API endpoint. That one returns a list of shops that I might be interested in, which is then presented to me on the page. I also get a map view, which potentially has other problem, but I’m not super interested in that at the moment.
The Coop site uses Google maps to provide this service. If you type your postcode in to this page then it sends that postcode to Google. You were never asked if you were happy for Google to know what postcodes you’re interested in.
Tesco offers the same thing. They use Mapbox APIs. Again, the postcode is sent to a different web server to the one that the main website came from, so your postcode searches are leaking beyond the one website that you’re using.
Plenty of other websites do exactly the same thing. B&Q is a chain of hardware and home improvement stores. They go a step further and guess your location based on your IP address. In most cases this is going to be a good guess. They’re probably using some API to do that too. But if you have a look at what they do with a postcode then you'll see they use another similar API from Woosmap. They then make an API request to a site called kingfisher.com to find the nearest stores. Kingfisher is the company that runs B&Q along with similar stores under different brands.
All these big chains are totally happy to ask for your postcode, and then send it off to some other web service you’ve maybe never heard of, or worse: Google, and use that to locate your nearest stores for your convenience.
There are companies that make money from buying and selling information like “This person, who you can identify by this web tracking cookie, likely lives near this postcode.” They build profiles of web users as they browse across many different websites, adding information to your profile as they learn new things.
If all they did with this data was target adverts, then that might not be concerning, but maybe your life insurance company is buying that data and deciding that you’ve been looking up your nearest Fast Food Chain a little too often. You’re a greater heart-attack risk than most. Looks like you’re gonna have to pay more for your life insurance.
I’m not saying that they’re all doing this. But when you consider that this is possible, it’s better to prevent that data being collected in the first place. A little aside: this is why the EU created a law that forbids websites from placing tracking cookies in your browser without consent. Lots of website operators decided that the appropriate way to comply with this law was to put intrusive and confusing popups on the page that make it easy to give consent, and not always as easy to deny consent. But today’s video is not really about that.
There’s lots of examples of websites that have these store locator features, but I’ve never seen one that is designed for privacy. I would love to come across a website with a store locator that verifiably did not let my postcode escape from my web browser in to some random web service. This means that the postcode can’t be allowed to get out of my web browser at all.
I would love this so much, in fact, that I decided to make it happen. I did it not just to prove that it is possible, but to provide the resulting tool for free to anyone that wants it.
UK Postcodes - What you need to know
There’s currently almost 1.8 million active postcodes in the UK. Each one holds a small number of addresses. Sometimes a postcode has a single address inside it. Sometimes a postcode maps to an entire street with tens of addresses.
Postcodes are deliberately constructed such that no house name or number is duplicated within a single postcode. This means that, technically, if you send a letter to 10, SW1A2AA, that will be delivered to the UK Government headquarters. You don’t need to write “Downing Street” on your letter. You don’t need to write “Westminster” or “London” on it either. The postcode and door number is sufficient.
It’s still a good idea to include those details when you send a letter or package. They provide some redundancy.
Every UK postcode is made up of two parts. The first part is called the Outward code, the second part is the Inward code.
-----------------------------------------
| Postcode | Outward code | Inward code |
-----------------------------------------
| B11RS | B1 | 1RS |
| B111RS | B11 | 1RS |
| SW1A2AA | SW1A | 2AA |
-----------------------------------------
The inward code is the simplest part. It is always 3 characters long. The first of these is a digit, then the last two characters are letters. These tend to be allocated sequentially, but not with much consistency. They start at 0AA, and continue with 0AB, and onwards until 9ZZ. They aren’t always all used. For example, for the Outward code of AB12, the lowest currently active Inward code is 3AA. There’s some small gaps here and there until it reaches AB12 5YX, and then a sudden jump to AB12 9AL.
The Outward code is everything except the last three characters. This code can be 2, 3, or 4 characters long. For example: B1 is the 2-characters Outward code for an area in the centre of Birmingham. B11 is a different area of Birmingham, and is 3 characters long. We’ve already seen a 4-character Outward code SW1A.
That Birmingham example is interesting though. It shows something that makes it tricky to parse a postcode. B1 1RS is a postcode for a shopping area in the centre of Birmingham. B11 1RS is a very similar postcode that is nearby, but it’s in a residential area of Birmingham. If you write these without the space between the Outward and Inward codes, as many people often do, then they both start with B11. Any system that parses a postcode should therefore not assume that a postcode that starts with a known Outward code is, in fact, located in that Outward code. Instead it should separate the Inward code first, since that’s always 3 characters long, and then parse what remains as an Outward code.

Okay, I think we understand enough to make something that works, so let’s get in to engineering a privacy preserving store locator system.
The way we’re gonna make this privacy-preserving is by avoiding sending any specific postcode over the internet to lookup its coordinates. This means that we need the browser to do all of the computation about the distance to each store from the postcode. Once the page is loaded, it should be possible to completely disconnect from the internet, and still use the store locator.
That means we need some way to know the GPS coordinates of every UK postcode without doing a lookup via a web service.
Getting the data
The key thing that we need is a complete mapping of UK postcodes to GPS coordinates. The Royal Mail has a complete mapping of postcodes to addresses. And they let you access most of it on their website. Strangely enough, when I tried looking for 10 Downing Street, it wouldn't tell me that the postode for it is SW1A 2AA.
Anyway, this database is called Postcode Address File (PAF). If I want a copy of it then I need to buy a license that costs thousands of pounds and needs to be regularly renewed.
The Royal Mail has monetised their postcode and address database!
Fortunately, there is a public body in the UK called the Office for National Statistics (ONS), who maintains an open database of all postcodes and the GPS coordinates of their approximate centres (where appropriate).
Since they're a public body, everything they do is open to the public. And they don't even make you do a Freedom of Information (FOI) request to get it!
The ONS provides a download that’s updated every few months with all the UK postcodes and their GPS coordinates.
If you thought it was going to be the Ordnance Survey (OS), that was a good guess. OS does provide a similar data set called Code-Point. In fact the ONS data set is actually based on the OS data set, but the OS version doesn’t include GPS coordinates, instead it provides UK National Grid coordinates.
The National Grid is the grid system that OS uses on their maps. (Not to be confused with the National Grid, which is the UK’s electricity distribution infrastructure.) The conversion from National Grid coordinates to GPS coordinates is not required if I use the ONS data set, so that’s why I chose that one.
I should clarify: the GPS coordinates are approximate. A postcode isn’t really a single point, it’s an area. It can be quite a big area. The Royal Mail even explicitly warns us about this on their website. Regardless, any point in that area is going to be a useful approximation for locating your nearest store.
The hard part (making it work)
Okay we have the data, can we just write some javascript that fetches that file ready to use offline, and when a user types in a postcode, it looks up the coordinates and then calculates the distance to each store?
No, not that easily anyway.
This file is 1.4GB! That’s enough to wipe out someone’s entire mobile data allowance in a single page load! That’s too big!
It contains a lot of fields we don’t care about. Let’s get rid of all fields except for the postcode, longitude, and latitude. As we do that, we can also discard any postcodes that have been terminated, and any that don’t have coordinates associated with them.
The file is now 48MB. That’s better, but it would still take about 5 seconds to download that over my home internet connection. It doesn’t sound like a lot for one user, but I want this to scale well. I don’t want to add a lot of additional load to the server, or consume excessive bandwidth. There’s also energy to consider too. I think it’s often overlooked, but coding for minimal energy usage is valuable.
Let’s take a closer look at how postcodes work. Earlier I explained how a postcode is an Outward code and an Inward code. If I want to optimise how I store them, I’m going to need to think about them as data. Below is a table of possible values for each position in the code
Position | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
----------------------------------------------------
| A-Z | A-Z | A-Z | A-Z | | A-Z | A-Z |
Options | | 0-9 | 0-9 | 0-9 | 0-9 | | |
| | |blank|blank| | | |
----------------------------------------------------
example | S | W | 1 | A | 2 | A | A |
----------------------------------------------------
# opts | 26 | 36 | 37 | 37 | 10 | 26 | 26 |
----------------------------------------------------
The Outward code always starts with a letter. The second character is either a letter or number, the third might not exist at all, but if it does, then it is a letter or a number. The fourth also might not exist, but can be a letter or a number.
To make parsing easier, you can always store postcodes in a fixed width format that is 7 characters long. You start with the Outward code. You then add 0, 1, or 2 space characters as padding, and finally add the Inward code.
Given this pattern, the first character has 26 possible values. The second has 36. The third has 37, if using the space-padding approach. The fourth has 37. The Inward code’s three characters have 10, 26, and 26 possible values respectively.
Now a hint of information theory. How many bits do we need?
26 × 36 × 37 × 37 × 10 × 26 × 26 = 8,662,155,840
log₂(8,662,155,840) ≈ 33.01
The total number of possible postcodes is about 8.6 Billion. That’s a super inconvenient number actually! This means you can’t quite store a postcode as a 32 bit integer. Even 33 bits is not enough, you need 34, but only just.
So far I haven’t made any assumptions based on which postcodes are actually in use, and I want to keep it that way. 8.6 Billion is the most postcodes we could have with this system. I want to avoid adding in any assumptions that reduce this space, so that this system continues to work in the future as more postcodes are added.
We’re gonna have to get creative about how to represent postcodes.
Making a better storage format
Let’s ditch the CSV format, and go for a raw binary representation. If I store each postcode as a number, then I can do that in 5 bytes. I need at least 34 bits, which is 40 bits if you round up to the next multiple of 8. 40 bits is 5 bytes, hence needing 5 bytes to store a postcode.
Given that the postcodes normally take up 7 bytes, this is a reduction of about 30%
While I’m doing that, I should also reduce the coordinates to a numerical representation too. Each one takes up about 9 characters in string form. A 64 bit floating point number would certainly be precise enough for a GPS coordinate, that costs 8 bytes. That’s not a big saving over the 9 bytes they were before. Perhaps we could use 32 bit floats, that way we need 4 bytes per number, that’s a lot better than 9! This is a reduction of 44%.
Overall, including the commas and newlines and whatnot, the postcode and coordinates in string form in a CSV file took 28 bytes per entry. With a packed numerical representation, which does not need the commas and newlines, this is reduced to 13 bytes per entry. This is less than half the initial size.
There’s a much better way to do this though.
Consider how a lookup works in this file:
The user has typed in a postcode, and wants to know if it is in the file. The search program needs to find that postcode in the file. The obvious simple algorithm to do this is to start at the beginning of the file, read the first postcode, see if it matches the typed postcode, and if not move on to the next entry in the file. Eventually you will hit either: the entry for the postcode you want, or the end of the file.
Scanning the entire file like this takes a significant amount of time. For the CSV version it’s about 740ms on average for a successful lookup. Sometimes it takes longer, sometimes it’s faster. It depends where in the file you find the postcode.
Another potential improvement we could make to the list of postcodes would be to reduce the amount of repetition in it. There’s a lot of postcodes that start with AB right at the start of the file. What if I had some way to insert information in to the file like “postcodes from this point on start with AB, only the last 5 characters are stored”. In that case I could remove the “AB” prefix, and save a little space.
One last idea to explore: A postcode does not define a point, it defines an area. The coordinates provided for a postcode are an approximate centre for the postcode area. Lossy compression is a category of compression where the data you get out of the decompression algorithm is not exactly the same as what you put in to the compression algorithm. The decompressed value is an approximation of the original value. Sometimes this is unacceptable, like when compressing text, such as the subtitles on this video perhaps. Sometimes this is acceptable, such as when compressing a photograph. If each pixel is almost the same colour as the original, you probably won’t notice, nor will you care. In the case of our coordinates, the values are approximate anyway, so perhaps some lossy compression is okay.
So here we have a few thoughts to guide the creation of a file format and algorithms for storing and looking up postcodes:
- Lookup time should be minimised.
- Prefix repetition could be avoided.
- Lossy compression of coordinates could be okay.
Let's take a look at that design now.
The Format and Algorithms in Detail
As the encoder program reads list of postcodes in to memory, and parses the coordinates for each one, it keeps track of the bounding box that surrounds all the postcodes. The program then pretends this is a square. It’s not actually a square, it's also not a rectangle, it’s actually a part of the surface of a spheroid, but the maths we’re doing doesn’t actually care too much about the shape since we're just going to do a transform that we are going to undo to get the original coordinates back later. It’s just a set of coordinates, we can visualise it as a square

So now we have longitude and latitude values for the edges of our conceptual square as 64 bit floating point values. These values go directly in to the file, right at the start.
Next, the encoder iterates over the postcodes, and for each one it splits the code into two parts. The first is the two character prefix, and second is everything else. Previously I said that you need 34 bits to store the postcode as a number. With the prefix removed, that reduces dramatically, to 24 bits. This is great because it fits very efficiently in three bytes.
Postcodes with two-character prefix removed
Position | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
----------------------------------------------------
| A-Z | A-Z | | A-Z | A-Z |
Options | 0-9 | 0-9 | 0-9 | | |
|blank|blank| | | |
----------------------------------------------------
# opts | 1 | 1 | 37 | 37 | 10 | 26 | 26 |
----------------------------------------------------
⌈log₂(37 × 37 × 10 × 26 × 26)⌉ = 24 bits = 3 bytes
The coordinates are then compressed with a lossy compression system. Below is the formula used to compress the latitude coordinate. The minimum latitude from the bounding box calculation is subtracted from the postcode’s latitude coordinate. This calculates the distance in to the box from the bottom edge. This is then divided by the height of the box. This results in a value in the range 0 to 1. This is then scaled up by multiplying by 65535, and rounding to the nearest integer. This results in a 16 bit number that represents a latitude in the bounding box.

The longitude is processed in a similar way, and now I can store the latitude and longitude in four bytes. This means that each postcode and coordinate entry is 7 bytes long, but doesn’t have the prefix included. This is another good improvement over the 13 bytes per postcode from before, and it’s only a quarter of the size of each entry in the CSV file.

The encoder processes all the postcodes like this and keeps a list of all of them. While it does this, it also keeps track of the prefixes in a table. The postcode table is sorted, so all of the postcodes with the same two character prefix will appear together. As it scans the list, any time a new prefix is encountered, it will put an entry in the table to indicate how many postcodes there were before the first one with that prefix.
Once all the prefixes are added to the table, the total number of postcodes is added at the end of the table, and all of the prefixes that were not used also get values in the table. The value of each of these unused prefixes is the value of the next prefix after that one in the table.
Example Prefix Table:
A0-AA: 0
AB : 0
AC-AK: 17,385
AL : 17,385
AM-B0: 25,185
B1 : 25,185
B2 : 30,800
B3 : 36,202
B4 : 42,028
...
(Ranges of the same value are fully expanded in the real file,
they are abreviated here only to fit more entries in the example)
Now the encoder writes the table values in to the file, and then all of the packed postcodes in order. And that’s it! The file is ready to go!
This file is about 12MB. That’s 25% of the minimised CSV file size. But how do we use this file?
Let’s have a look at the lookup algorithm next.
The first step of this algorithm is to make sure the postcode is correctly formatted. Some people will deliberately put a space in their postcode, between the Outward and Inward codes. Some people will try to put such a space in and get it in the wrong place. Some people use no spaces at all. Some people will use upper case, others will use lower case. Rather than require the user to type the postcode in the correct format, the algorithm just does this for them.
Formatting a postcode is fairly easy. First make sure all the letters are upper case, remove all the spaces that the user put in there, and then insert spaces between the Outward and Inward codes until you have a 7 character string. Since the Inward code is always 3 characters, it’s easy to find where to insert the spaces.
Of course, some postcodes are too malformed to recover them. If you miss some of the code, or include an invalid character, this step will cause an error.
Initial user input: "b 11 rs"
-----------------------------------
1. Upper case all chars: "B 11 RS"
2. Remove all spaces: "B11RS"
3. Insert correct spaces: "B1 1RS"
-----------------------------------
Well formed output: "B1 1RS"
Now we split the postcode up to get the two character prefix and the rest. We turn the prefix in to a number, and separately encode the rest of the postcode as a number just like the encoder did when it created the file. Now we can parse the file. It starts with the bounding box coordinates, which are easy enough to read. Then we use the prefix number to look up where to start scanning for the postcode in question. Because of the way that this part of the file was constructed, we can be sure that the next number in the table after this one represents the furthest we would ever need to scan to find a postcode with this prefix, so we make a note of that too.
Postcode: "B1 1RS"
Prefix: "B1"
Suffix: " 1RS"
Numbers from prefix lookup table:
Lookup start point: 25,185
Lookup end point : 30,800
Now we multiply these numbers by 7, since that’s the length of each postcode, and now we know the byte offsets in to the file where we should start and stop scanning. Calculating the distance to the end of the table, and adding the start offset allows us to know where to seek to, skipping lots of postcodes that have other prefixes.
Now we just need to grab each postcode in sequence, and compare it to the number we calculated at the start. If the postcode doesn’t exist, then we will hit the end of the search range. If it does exist, then we will find a match, and can then reverse the calculation done on the coordinates to compress them.
The coordinates can’t be retrieved exactly, because there was some rounding involved in calculating them, and possibly some floating point errors too, but the results are typically within a few metres of the actual values. Certainly precise enough for something as approximate as a postcode.
This lookup process is able to skip over lots of postcodes without even reading them, this makes it much faster than a lookup in the CSV file. The average lookup time is reduced from 740ms to only 3.3ms. This is a huge saving! Three quarters of a second is long enough to notice, but a few milliseconds is barely perceptible. This is certainly fast enough.
Notice that this speed up is much more than you’d expect just from the file being shorter, so clearly the structure and lookup algorithm had a big impact too.
Remember those three things from earlier: Lookup time should be minimised. Prefix repetition could be avoided. Lossy compression of coordinates could be okay.
Designing with these in mind produced a much smaller and faster solution, but I’m not done yet!
We have to go deeper go smaller!
That lookup time is excellent! In fact, it’s so good, that I think it would be acceptable to trade off a little bit of lookup time for an even smaller file size. 12MB is still a bit too big to expect a casual user to be okay with.
So here’s another thing to consider: The postcodes are sorted, and they come in densely packed clusters. There’s big gaps between the clusters, but within each cluster it’s easy to predict what postcode is going to come next.
This encoding scheme is what I’m calling the delta encoding. Some of the values in the file are not stored in absolute numbers, they are instead stored as a delta on top of the previous value in the file.
Previously a postcode was a fixed 7 byte structure, now it’s going to vary in length. The postcode is normally 3 bytes, and the coordinates are normally 4 bytes. If the coordinates are close enough to the previous ones, then I could instead store a pair of 8 bit signed integers that are added to the previous coordinates to get the next coordinates. The postcodes are sorted, so I never need to go backwards, so for the postcode delta I can store an unsigned number. I decided to limit this number to 6 bits, which will make sense soon, giving the delta a range of 1 to 64.
Now the structure has four different formats. The first byte determines which format is used. Bits 7 and 6 of the first byte are flags that indicate which fields are delta encoded. If bit 7 is set, then the postcode is delta encoded. If bit 6 is set then the coordinates are delta encoded. So the worst case scenario is when neither is delta encoded. The first byte just has the value 0, and then the next 7 bytes are the postcode and coordinates in the same format as before. This takes up 8 bytes, so it’s actually slightly worse than before, but that’s fine because the next three cases are far more common.
If the postcode is delta encoded, then the delta to the next postcode is stored in the last 6 bits of the first byte. The coordinates then appear immediately after this. If the coordinates are not delta encoded then this case is only 5 bytes in total.
Perhaps only the coordinates are delta encoded, in which case it’s 6 bytes in total.
Finally, the best case is when both of them are delta-encoded, for this case I only need 3 bytes to store the entire entry. It turns out that 91.9% of all the postcodes can be encoded in the 3 byte format, and only about 0.37% of them need to be stored in the fully expanded format.

This saves a lot of space! The new data file is only 5.5MB.
This encoding scheme is much more complicated, and so the lookup time does suffer a little bit. The lookup algorithm needs to be modified to handle the delta encoding. It needs to keep track of the previous postcode and coordinates as it scans the file. It needs to parse the structure to figure out how to update its internal state, and to know how far to move the cursor onwards.
Previously it was always moving by 7 bytes, now it might be 3, 5, 6, or 8.
So how big is the effect? Well the average lookup time with this method is about 6.6ms. Despite the file being less than half the size it was before, the lookup time has doubled! That’s unfortunate, but it is still really fast. It’s still in the barely perceptible range. Looking at the graph we can see that both of these formats handily beat the CSV format.

Getting speed gains has been much easier than getting space gains, but I’m happy with the delta encoding scheme’s size and speed.
A Fun Demo
So, getting back to the problem I wanted to solve, let’s have a look at a little demo that uses this system to do a privacy preserving locator tool.
If you open that page and then open the developer tools window of your browser (normally F12), then you can see the magic happen. Clear everything from the network requests tab after loading the page but before enabling the search tool. (Since it needs to download a file that is slightly abnormally big for a website, I thought it best to make sure the user is aware that they’re about to download it.)
Clicking the button, you can see that the file download shows up in the network requests tab. And now the search tool is enabled. At this point, you could totally disconnect from the internet, and this would still work. Type in a postcode, press search, and you'll see a list of all the Automobile Association Call Boxes sorted by their distance to that postcode. Notice that no additional network requests were made, the lookup happened offline.
In a real world scenario, I might expect one additional network request to occur when the search tool loads, to load the list of locations, but that can also happen before the user ever types a postcode, and still preserve privacy and allow offline use. In this demo the list is trivially small and is loaded as part of the script on the main web page.
I’m just some person on the internet with almost zero clout, so I’m not really expecting any big corporation’s website to start using this any time soon. But if you happen to be someone who makes technical decisions for such a website, I would love to be able to say I’ve convinced you to switch to this approach.
I’ve only just finished making this work in my demo, so there’s some practical considerations that I still need to figure out for large scale deployments. If you have useful ideas or feedback regarding that, then please let me know by submitting an issue.
The code is open source and currently hosted on Codeberg. You can also find it on Github.
Closing thoughts
Before I go, I want to leave you with some thoughts about privacy and technology. Big tech companies that provide web based services have big incentives to sell your personal data. This isn’t something that is inherent in technology. I hope that what I’ve shown here has demonstrated that effectively.
Technology can be applied in ways that preserve privacy if the people creating that technology endeavour to make it that way. Big tech companies generally don’t do that.
I hope I’ve also demonstrated that it’s worth being frugal with energy and data. Spending that extra effort to minimise the size of a file means that the file can be delivered much quicker and with less energy. Spending the time to minimise the computation required to process it also reduces the energy used.
Sometimes it’s a small effect, but it could multiply up to something much bigger.
Maybe I’ve inspired some of you to apply a similar ethos to the way you write code. That’d be nice.
Part of a series of posts: Next in series >



















