Is this username taken? Find out before querying your database (#dev #bloomfilter #dataStructure #benchmark #csharp)

Practical guide on how to run AI decision models locally.

Overview

So you have a very popular app, and it grows and grows a bit more every day. However, every time a new user signs up, you have to check if the username is available. Let's say you currently have 4 million users. So every time a new user is deciding which username they want, you make a round trip to your database to see if that username is already taken. One check is cheap, but people try a few names before settling, and a lot of those names were never in your database to begin with. On top of that, you're planning on growing to 6 million users soon, so the problem will only escalate.

If you're more on the technical side, a pile of round trips that come back empty-handed probably sounds like something that either already is a bottleneck or will soon become one. In this post we talk about a way to solve this with a pretty neat alternative.

So, what if I told you there's a way to know for sure that a username is available, without even looking in the direction of your database? The catch is on the other side: when it says a username might be taken, that's only "high confidence", which means it will sometimes miss. In this case, a miss means 1 query to your database that you could have skipped, but instead of making a round trip for each username a new user tries, you only check the database if the username might be taken. If 90% of the usernames people try to use don't exist, this represents a theoretical reduction of about 90% of the queries you would make.

That's where something called a Bloom filter comes in. It is a clever little data structure that can tell you if something is definitely not in a database, or probably is.

To demonstrate this, I created a benchmark for this post comparing 3 approaches:

  1. No Bloom Filter; just querying the database every time.
  2. Hand-rolled Bloom Filter: Created my own implementation, mostly to demonstrate how it works.
  3. Bloom Filter library: Used the package BloomFilter.NetCore, since it is a popular and well-maintained library.

Is the Bloom filter useful for anything else besides checking if a username already exists in a database?

I'm glad you asked that, and yes! Two other notable use cases (also listed in the Redis Bloom Filter Documentation) are:

  1. Fraud detection in payment processing: One filter per customer, holding the places they have paid from. For every transaction, ask "has this user paid from this location before?". A "definitely not" is certain, so that transaction gets a closer look. The same idea answers "has this card been reported stolen?".
  2. Ad placement: Also one filter per user, holding the ads they have seen or the products they have bought. Before showing an ad, check it. "Definitely not" means show it and add it. "Maybe" means pick another one. In this case nobody confirms the "maybe" against a database. A false positive costs one ad that a user never gets shown, and that's cheap enough to accept (in theory).

What is a Bloom filter?

Putting it simply, a Bloom Filter is a data structure represented by an array of bits (a map) and a hash function that picks a few positions in it for each value. As more users join, you add values to it, and then check new values against that map. With it, the question of "Is this username taken?" can have one of two answer:

  1. Definitely not: This is never wrong.
  2. Maybe yes: This can be wrong. Out of the usernames that were never added, a share that you decide (1% for example) gets this answer anyway.

Dipping our toes a bit more in the technical side, the Bloom Filter supports two operations: Add(value) and MightContain(value). Both relying on an array of m bits and k hash positions per value.

Sounds like something too simple, right? But that's the beauty of it because with just those, it guarantees:

  1. No false negatives: Whenever MightContain(value) returns false, the value was never added to the map.
  2. You tune p to control the false positive rate: When MightContain(value) returns true we have two options:
  • The value was added to the map
  • The value was never added, but all of its k bits were set by other values.
  1. Fixed memory: Size depends on the number of values you planned for (n) and on p, not on how many values are actually in the map.

Fun fact: The concept of Bloom Filters were first introduced in July 1970 by Burton Howard Bloom. He published the original concept in Communications of the ACM, with the paper "Space/Time Trade-offs in Hash Coding with Allowable Errors" Paper PDF: https://crystal.uta.edu/~mcguigan/cse6350/papers/Bloom.pdf

Wait, what all those letters mean?

I mentioned a bunch of letters, and I can see the whole explanation getting more convoluted, and throwing people off. Let me bring you all back with this simple breakdown of all those loose letters:

LetterWhat it isIn the context of the "Is username taken?" example
nHow many items you're planning to put into the map6 million usernames
pThe false-positive rate. So how often a value that isn't there gets a "maybe"1%
mHow many bits the filter (map) has57.5 million bit (around 7MB)
kHow many bits each value sets and checks7

You decide on n, and p, then the formulas give you m and k.

Hm... I still don't get it. This is still confusing.

I can almost hear some of you saying: "Hey Raccoon, this sounds interesting, but looks very complex, It is hard to understand, so I don't know if it is worth investing time in it. Maybe I'll just ask Claude to make no mistakes while fixing it, and call it a day."

If you're in this group, no problem. If you're not familiar with the concept, it is a bit hard to understand it at first, so let me try explaining it with an analogy.

Imagine that your city's public library keeps all the old books it has in an archive located in their basement. This archive is kind of far, like 10 minutes away from the front desk, so every time someone asks for a book, the librarian walks down, searches the shelf, and walks back. And more often than not, she comes back empty-handed, because most of the books people ask for were never in the collection.

So she makes a sheet of paper with a thousand empty checkboxes and tapes it to the desk. When a book arrives, she uses a special rule that picks 3 checkboxes and ticks them. The special rule is: the same title always gives the same three boxes to tick.

With this, if someone asks for a book, she runs the target through that rule, and checks if all 3 boxes are ticked. If not, she knows she doesn't have the book without leaving her desk.

Only if all three boxes are ticked, she goes to the archive and looks for the book. Sometimes it will happen that all three boxes were already ticked by other titles, so she will come back empty-handed anyway, but most of the time it will work, but it works so well that she will be able to handle way more requests than before.

In this example, the Bloom Filter is sheet the librarian printed, the basement archive is your database, adding a title by ticking the boxes is the Add(value), and looking for a title by checking if the 3 boxes are ticked is the MightContain(value).

Common Questions about how it works

  • Does the filter stores the usernames? No. It stores marks left by that value in the map. You can't get a username back out of it.

  • Why is "definitely not" always right, but "maybe yes" is not? Adding a new username leaves all of its marks in the map, and marks are never erased. If a value comes back with at least one mark missing, then it was never added to begin with.

On the other hand, the "maybe yes" can be wrong because the marks each value leaves are shared, so in some instances a username that was never added lands only on marks left by other usernames.

  • How often is it wrong? As often as you decide. I know that's a weird thing to say, but think of it like this: The more space we set, the fewer shared marks will exist. At 10 bits per name, around 1 in every 100 usernames that were never added gets a "maybe yes" anyway. Just keep in mind that this rate is about the names that are not in the map. It isn't how often a "maybe yes" is wrong: if nearly every name you check doesn't exist, a big share of the few "maybe yes" answers you get will be false alarms.

  • Can I delete a name from the map? No, because deleting the marks left by a specific username might impact other values that share the same marks. If we do this, the filter might start to fail on one thing it promises: That when it says the username is not in use, it is always right.

  • What happens after the Bloom Filter responds with a "Maybe yes"? That's when you ask the database to be sure.

  • What happens if I add the same value twice? Nothing because the values themselves are not added. To pull from the librarian analogy we used before, if you try to add the same title to the sheet of paper twice, the title, once it passes her special rule, will land on the same bits, so nothing changes.

  • Why do we need that p for false positives? It makes sense to ask that. Why do I need to set that value to something? Why not just say "0% false positive" and call it a day? The answer is balance. Bloom filters trade accuracy for memory efficiency. So the lower you set p, the more efficient it becomes, but it also consumes more memory. The opposite is also true. So, even if you want, 0% is not an option. And the reason is, as the filter uses more and more bits (unbounded) to be more accurate. To achieve "always correct" status you would basically need to add all the usernames to memory and keep it updated.

Limitations

There are 4 main limitations worth knowing about:

  1. It can give false positives: Some values that were never added might come back as "maybe".
  2. It can't delete values from the map: Deleting values would mean removing bits from the map, those bits could be used by other values.
  3. It can't list the contents: There's no way to use the filter map to list back all the usernames it "knows", because it only holds bits, and not the actual values.
  4. If you add more values than anticipated, quality degrades: As most things in life, if you use it say you'll add 4 million values, and then you start adding more and more past the limit, the rate of false-positives will raise.

Where does this map live?

Well, in memory. That's why it's so fast.

Where it comes from can vary, depending on the strategy we want to use:

  1. Rebuild it from the database at startup.
  2. Load it from a file you created earlier.
  3. Keep it in a shared store like Redis (which has a built-in Bloom Filter, by the way)

Each of those options comes with a figurative cost:

OptionStartup costPer-check costShared between instances
Rebuild from databaseFull scan of the all usernamesMemory readsNo. Each instance has its own
Load from file snapshotRead a few MB, then catch upMemory readsNo. However, each instance loads the same file
Using RedisNoneOne network round tripYes

The options that are not shared across all the instances also need a feed of new keys, otherwise, a user added via Instance-1 will be unknown to Instance-2.

The consequence for this (map not shared across instances) is that if someone registers with username "username-A" via Instance-1, and then they try to register again with the same username, and this time the request lands on Instance-2, and it will in the registration going through because Instance-2 doesn't have "username-A" in its map. This new request will only fail at a later point, when the database refuses the duplicate. That's why the unique constraint on the username column stays where it is: the database is the source of truth, and the filter only saves trips to it. Even with a shared map, two people asking for the same free username at the same moment would both get a "definitely not".

While this makes for a poor user experience, depending on the type of application you have, it is an acceptable risk to have, if you don't want to deal with "new user feed" to sync the instances.

Wait, did you just say that this map would live in an actual file?

Yes, I said that. And yes, I also see the irony in talking about something that will work around slow I/O requests, just to suggest using an actual file saved to disk, but it makes sense, I swear!

The thing is: The file is used to load the map to memory, all at once. Not to be used during runtime. So this strategy saves you the effort to rebuild the whole map during startup.

Considering our example of 6M user example would result in a ~7MB file being loaded to memory, which is way faster than reading 6 million usernames from a database.

Thinking about scalability here, if we decide to use this, how big should we expect the file to get? Without getting technical, to have an average estimation, consider 1.2 bytes per planned value (at a 1% false-positive rate), so for each 1 million users you can expect 1.1 MiB.

To look at this from a more technical perspective, let's consider the bits in the maps as ulong words (because that's what we used in the snippet), so to calculate the size of a map file in this case, we could use:

1file bytes = 8 * ceil(m / 64) + header

In this example, m is the bit count from the sizing formula. At a 1% false-positive rate:

Design count (n)Bits (m)WordsArray bytesSize
1 million9,585,059149,7671,198,1361.14 MiB
6 million57,510,351898,6007,188,8006.86 MiB
12 million115,020,7011,797,19914,377,59213.71 MiB
24 million230,041,4023,594,39728,755,17627.42 MiB

How do we keep all instances synced?

Considering a use case where the maps live in memory, so they are not shared across instances, we have a job to do: maintaining all instances synced.

Recapping: The filter map is a copy of something (in our example, usernames) in our database, and, overtime, this copy will drift:

  • If the filter has a name the database doesn't (like a deleted user), no big deal. The app will get a "maybe", and we'll call the database.
  • If the database has a username the filter doesn't, then we have a bug. In this case, the filter will result in "definitely not", so the app tells the user that a taken username is free, and the sign-up only fails later, when the database refuses the duplicate.

This gives us an insight of what would happen if the map and the actual values in the database start to drift / fall out of sync, but how do we keep them in sync?

While we don't need to overthink this (since all we need is a feed with new values), I think the most appropriate solution will depend on how your system currently works, but I can give some suggestions:

SuggestionLagCan it lose a value?Extra moving pieces?
Poll the databaseUp to one poll intervalOnly if rows commit out of order and the poll skips themNone
Pub/Sub Topic (Like Azure Service Bus)One network hopNot once publishedA message broker
Event Stream (Like Azure Event Hubs)One network hopNot once publishedAn Event Hub
Durable log (like Kafka)One network hopNot once publishedA broker with retention
Database change streamDepends on the databaseNoA stream reader

One detail for the options that use a broker: every instance needs to receive every new username. A plain queue hands each message to a single consumer, so only one instance would learn about the new user. Use a topic with one subscription per instance (or one consumer group per instance, on Event Hubs and Kafka).

If we can reuse existing infrastructure, all the better. Otherwise, trying the Database change stream or Event Hub (if you're on Azure) could be good candidate that won't raise the cost too much. But do your homework first, and check scalability, availability, and pricing before pulling the trigger.

Practical example (C#)

In the snippet I created, one of the things I did was to use a hand rolled Bloom Filter algorithm to show how it works. It is a very naive example, but I think it gets the point across.

The snippet also uses the BloomFilter.NetCore package, and you can check how to use both there.

To initialize it, we would do something like:

1var filter = new HandRolledBloomFilter(expectedItems: 6_000_000, falsePositiveRate: 0.01);

Then we add the usernames:

1filter.Add("john.doe");

And we can check if they were added:

1filter.MightContain("john.doe"); // true
2filter.MightContain("carl");     // false, or true about 1% of the time

Lastly, we put this check in front of the call to the database, like this:

1public UserCheckOutcome Check(string username)
2{
3    return filter.MightContain(username)
4        ? LookUpInDatabase(username)
5        : UserCheckOutcome.RejectedByFilter;
6}

Don't let the name RejectedByFilter confuse you: it means the filter is sure the username is not in the database. For a sign-up, that's the good news, because the username is free.

We talked a lot about how it works, but in practice, the usage is not that complicated.

(Link to the full snippet, and references at the end of this post)

Benchmark

The idea of the benchmark is to answer the following question: In practice, how much faster is the "Is this username known?" with a Bloom Filter in place?

To keep the benchmark simple and portable, I used a SQLite database, which is created on-the-fly, with millions of records.

If you want to test it yourself, after cloning the repo and accessing the snippet folder, you can run the following commands:

1dotnet run -c Release -- benchmark
2dotnet run -c Release -- benchmark-scaling

Each is a different benchmark, focusing on a different aspect. However, in all of them, the target false-positive rate is 1%.

Test cases

Filter comparison

In this benchmark, we run 8 million checks against an in-memory table of 6 million users, and 20% of the usernames checked exist. We tested 3 perspectives in here:

  1. No Filter: So accessing the database directly.
  2. Hand-rolled Bloom Filter: Using the filter I created for this demo.
  3. BloomFilter.NetCore: Using the filter available in that package.

Scaling

This one is a bit different: We execute 1 million checks against an on-disk table, in two modes:

  1. No Filter: So accessing the database directly.
  2. Hand-rolled Bloom Filter: Using the filter I created for this demo.

For each mode, we have a combination of:

  • Table size: 1, 6, or 24 million users.
  • Share of checked usernames that don't exist: 0%, 50%, 90%, or 99%.

Benchmark Results

Filter comparison

  • Checks: 8 million
  • Usernames unknown: 80%
  • Total usernames: 6 million
MethodMeanErrorRatioAllocated
NoFilter39.86 s0.62 s1.0010.37 GB
HandRolledFilter9.78 s0.20 s0.252.16 GB
ThirdPartyFilter10.23 s0.37 s0.262.75 GB
CaseTimeSpeedup
No filter39.9 s1.0x
Hand-rolled9.8 s4.1x
BloomFilter.NetCore10.2 s3.9x

So, did the Bloom Filter worked for this one? Yes, and it was a pretty straightforward comparison: Checking 8 million usernames took 40 seconds without the filter. With it, the results were close: 4.1x faster with our hand-rolled implementation, and 3.9x with the 3rd party library.

I wouldn't read much into the difference between them: the two results are within each other's error margin, so I'd call it a tie.

Scaling

UsersUnknownNo filterFilterSpeedupCeilingSaved per check
1M0%4.74 s4.80 s0.99x1.00x-0.06 µs
1M50%4.70 s2.46 s1.91x1.98x2.24 µs
1M90%4.59 s0.62 s7.45x9.17x3.97 µs
1M99%4.72 s0.18 s25.6x50.2x4.54 µs
6M0%8.83 s8.80 s1.00x1.00x0.03 µs
6M50%8.53 s4.59 s1.86x1.98x3.94 µs
6M90%8.70 s1.12 s7.75x9.16x7.58 µs
6M99%8.66 s0.23 s38.0x49.9x8.43 µs
24M0%11.04 s11.75 s0.94x1.00x-0.71 µs
24M50%10.50 s5.55 s1.89x1.98x4.95 µs
24M90%10.65 s1.33 s8.01x9.17x9.32 µs
24M99%10.53 s0.33 s32.4x50.1x10.20 µs

Speedup of the hand-rolled filter over no filter:

Users0% unknown50%90%99%
1M0.99x1.91x7.4x26x
6M1.00x1.86x7.7x38x
24M0.94x*1.89x8.0x32x

What these tables mean:

  1. Users: Number of users in the database
  2. 0% Unknown: The filter says "maybe" every time, SQLite gets asked anyway, and the run takes the same time with or without the filter.
  3. 50%/90%/99%: Percentage of the checked usernames that don't exist in the database.
  4. Ceiling: The best speedup possible if the filter itself cost nothing. Only the usernames that exist, plus the 1% of false positives, would reach the database.
  5. Saved per check: The time difference between the two modes, divided by the 1 million checks.

I expected to see a small penalty here and mostly couldn't find one. The cell marked * looks 6% slower, but its measurements wobbled by far more than that from one pass to the next, so I don't trust the gap. That column is the consequence of a filter that has nothing to skip: nothing gained, next to nothing lost.

At 50% the run is not quite twice as fast. At 90% it's seven to eight times. At 99%, where nearly every check is a miss, it's 26 to 38 times.

Now read it top to bottom: The table size barely moves the ratio. What it changes is how much time each skipped lookup is worth. Without a filter, a check costs about 4.7 µs on the 1M table and about 10.7 µs on the 24M table, most likely because the big table doesn't fit in SQLite's cache. So at 90% unknown the filter saves about 4 µs per check on the small table and about 9.3 µs on the big one. A similar ratio, and more than twice the time back.

Also take those numbers with a grain of salt: The SQLite database created for this was always brand-new, no poorly maintained indexes, didn't have rows being added and deleted, etc. And the main one: SQLite runs inside the same process as the benchmark, so there's no network round trip. In a real production database, every lookup pays for one, so the gaps would probably be bigger. On the flip side, we are talking about microseconds saved per check here, so the filter pays off when you have a lot of checks, or expensive ones.

When to use the Bloom Filter

When you want things to go fast, of course! Just kidding, let's think things through...

A good rule of thumb would be to use it when:

  1. The database lookup behind it is expensive compared with a few memory reads.
  2. Most database lookups are for things that aren't there.

On the other hand, we should avoid using it when:

  1. Most database lookups find something.
  2. The store being looked at is already as fast as the filter (like an in-memory dictionary)
  3. You need to delete things often
  4. For your application, a wrong "maybe" is unacceptable, and you wouldn't be able to do the actual check if you used the filter.

I believe that's a good starting point to evaluate if you should use the Bloom Filter or not.

Well, that's it. I hope it helps. If you want, check the snippet I made to see it in action.

References

Translations: