import java.util.BitSet;
class BloomFilter {
private final BitSet bits;
private final int m; // number of bits, e.g. ~17 billion
private final int k; // number of hash functions, e.g. 7
BloomFilter(int m, int k) { this.m = m; this.k = k; this.bits = new BitSet(m); }
// Kirsch–Mitzenmacher: simulate k independent hashes from just two
private int position(String name, int i) {
int h1 = murmur(name, 0xA5A5);
int h2 = murmur(name, 0x5A5A);
return Math.floorMod(h1 + i * h2, m);
}
// called once, when a signup succeeds — bits only ever turn ON
void add(String username) {
for (int i = 0; i < k; i++) bits.set(position(username, i));
}
// false → DEFINITELY free. true → only "maybe taken", go ask the DB.
boolean mightContain(String username) {
for (int i = 0; i < k; i++)
if (!bits.get(position(username, i)))
return false; // one 0 bit is proof of absence
return true;
}
}
// GET /check?u=... — fired (debounced) while the user types
String checkUsername(String u) {
// 1. RAM only — settles most genuinely free names in <1µs
if (!bloom.mightContain(u)) return "AVAILABLE";
// 2. the filter said "maybe": now ONE real lookup is allowed
Boolean cached = redis.get("uname:" + u); // hot names stay cached
if (cached != null) return cached ? "TAKEN" : "AVAILABLE";
// 3. sharded by hash(u), hits an index — cheap, but not free like RAM
boolean taken = db.exists("SELECT 1 FROM users WHERE username = ?", u);
redis.set("uname:" + u, taken, Duration.ofMinutes(5));
return taken ? "TAKEN" : "AVAILABLE"; // a false positive exits here
}
// after a successful signup:
db.insert(newUser); // DB first — the source of truth
bloom.add(newUser.username); // then flip the bits on