DEV Community

Nilesh Raut
Nilesh Raut

Posted on

Bloom Filter with Express.js

Ever struggled with users registering the same username again and again? Or maybe your app’s registration checks slow down because of repetitive database lookups?

Let’s talk about a super-lightweight solution — the Bloom Filter. 🚀


💡 What’s a Bloom Filter?

A Bloom Filter is like a smart checklist. It doesn’t store actual data — just tiny memory bits that say whether something might exist.

When a new username comes in, it gets passed through multiple hash functions, and the results mark specific spots in a bit array.
Later, when the same username is checked, the Bloom Filter instantly knows if it probably exists.

No need to hit your database for every check. ⚡


⚙️ A Real Example in Express.js

When I built my eCommerce website, I used a Bloom Filter to block duplicate usernames during registration.

Here’s a simplified version of my setup (no classes, just functions 👇):

const crypto = require("crypto");
const FILTER_SIZE = 200;
const bloom = new Array(FILTER_SIZE).fill(0);

function getHash(value, seed) {
  return parseInt(
    crypto.createHash("md5").update(value + seed).digest("hex"),
    16
  ) % FILTER_SIZE;
}

function addToBloom(value) {
  [1, 2, 3].forEach(seed => bloom[getHash(value, seed)] = 1);
}

function mightExist(value) {
  return [1, 2, 3].every(seed => bloom[getHash(value, seed)] === 1);
}
Enter fullscreen mode Exit fullscreen mode

Then in my registration route:

app.post("/register", (req, res) => {
  const { username } = req.body;
  if (mightExist(username)) return res.status(400).json({ message: "Username probably exists!" });

  addToBloom(username);
  res.status(201).json({ message: "User registered successfully!" });
});
Enter fullscreen mode Exit fullscreen mode

That’s it! In less than 30 lines, you’ve got a fast, memory-friendly duplicate checker.


🔍 Why This Works

  • 💾 Uses almost no memory
  • ⚡ Works in O(1) time (super fast lookups)
  • 🚫 Avoids repetitive DB queries

Just remember: Bloom Filters may give false positives (rarely), but never false negatives.


📘 Quick Example – "nileshblogtech"

When you register "nileshblogtech":

  • It hashes 3 times → sets bits at 27, 83, and 141 to 1.
  • Next time you try the same name, those positions are already 1 — boom 💥 “Probably exists!”

🧭 Final Thoughts

Bloom Filters are small but powerful.
If you want to make your backend faster and smarter, especially for checks like usernames or emails, they’re a perfect fit.

👉 Read the full guide (with dry run, diagrams, and advanced tips):
Full Article: Bloom Filter in Express.js – Complete Guide

Top comments (0)