Skip to main content

A pure Python, zero dependency bloom filter.

Project description

VSTG

VSTG Skips Table Gets

A pure Python, zero dependency bloom filter, built so a check that would otherwise hit your database on every request almost never has to.

The name is also short for vestige, a trace left behind by something that passed through, which is what the underlying bit array actually is.

The problem this solves

Before:

def check_username(request):
  username = request.GET["username"]
  taken = User.objects.filter(username=username).exists()
  return JsonResponse({"available": not taken})

After:

import vstg

def check_username(request):
  username = request.GET["username"]

  if not vstg.might_contain("usernames", username.encode("utf-8")):
    return JsonResponse({"available": True})

  taken = User.objects.filter(username=username).exists()
  return JsonResponse({"available": not taken})

Every username that was never registered returns without the database being touched. The rare "maybe" still runs the exact same query as before, so correctness never changes, only how often the expensive path is needed.

Install

pip install vstg

No dependencies are ever installed alongside it.

For contributing, clone and install in editable mode instead:

git clone https://github.com/vszlx4/vstg.git
cd vstg
pip install -e '.[dev]'

Usage

from pathlib import Path
import vstg

vstg.init(Path("bloom_state"))
vstg.register("usernames", capacity=10_000_000, error_rate=0.001)

vstg.might_contain("usernames", username.encode("utf-8"))  # check
vstg.add("usernames", username.encode("utf-8"))            # record

init and register run once, at startup. might_contain and add run everywhere else, for the life of the process.

Customization

vstg.register(
  "usernames",
  capacity=10_000_000,
  error_rate=0.001,
  policy=vstg.PersistPolicy(
    checkpoint_interval_seconds=300,
    checkpoint_insert_threshold=50_000,
    checkpoint_on_shutdown=True,
  ),
)

vstg.register(
  "email_verification_tokens",
  capacity=500_000,
  error_rate=0.01,
  shard_count=8,
)

Every named filter is independent, its own capacity, error rate, and policy. shard_count, left unset, gives a single checkpoint file. Set it and a checkpoint only rewrites the shards that actually changed. Capacity, error rate, and policy are fixed the moment register is called, for the rest of the process.

The math

A filter is a bit array of length $m$, all bits starting at $0$. Inserting a member sets $k$ of those bits, each position derived by hashing the member. Checking a member reads the same $k$ positions: any bit still $0$ proves the member was never inserted, since insertion only ever sets bits. All $k$ bits set means probably inserted, since an unrelated combination of other members could have set the same positions by coincidence.

Sizing, given an expected item count $n$ (capacity) and a target false positive probability $p$ (error_rate):

$$ m = -\frac{n \ln p}{(\ln 2)^2} \qquad\qquad k = \frac{m}{n} \ln 2 $$

optimal_size and optimal_hash_count in core.py compute exactly these two values.

Bit positions, rather than running $k$ separate hash functions, two hashes are computed once and every position derived from them (Kirsch-Mitzenmacher):

$$ i_j = (h_1 + j \cdot h_2) \bmod m, \qquad j = 0, \dots, k-1 $$

Resulting false positive rate, after $n$ insertions into an $m$-bit array with $k$ hash rounds:

$$ p \approx \left(1 - e^{-kn/m}\right)^k $$

The sizing formulas above are exactly this expression solved for the $m$ and $k$ that minimize it at the requested $n$ and $p$. Exceeding the configured capacity degrades the real rate past what was requested, since $n$ in this formula grows while $m$ and $k$ stay fixed.

Full API

  • BloomFilter — the bit array, add, might_contain, in memory only.
  • ManagedBloomFilter — a BloomFilter plus automatic checkpointing.
  • ShardedBloomFilter — checkpointing partitioned across shard files.
  • BloomFilterRegistry — the named collection vstg.register uses internally.
  • PersistPolicy — checkpoint trigger configuration for all three above.

Contributing

Two space indentation, mypy --strict, no runtime dependencies, a docstring on every module, class, and function.

git clone https://github.com/vszlx4/vstg.git
cd vstg
pip install -e '.[dev]'
python -m unittest discover -s tests -v

License

MIT, see LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

vstg-0.1.1.tar.gz (33.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

vstg-0.1.1-py3-none-any.whl (24.2 kB view details)

Uploaded Python 3

File details

Details for the file vstg-0.1.1.tar.gz.

File metadata

  • Download URL: vstg-0.1.1.tar.gz
  • Upload date:
  • Size: 33.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.8

File hashes

Hashes for vstg-0.1.1.tar.gz
Algorithm Hash digest
SHA256 3aeeba2ea8c009239e9dd25620bf7e7278277332938f293d1cc24e19dc54f1f2
MD5 d41dd5248cf2fc1593ebbf9f07d19447
BLAKE2b-256 2ac16dd7d3dcd4109cc2fb4ce601a3cbdb136631453c49659998b53fc5c548c0

See more details on using hashes here.

File details

Details for the file vstg-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: vstg-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 24.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.8

File hashes

Hashes for vstg-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 cb918aa1af0b49b55642cf3411e8877a3b683c9cf099afdd8bbef9509f59e453
MD5 7d097ab5b105218dbd13a858fcb6c5b5
BLAKE2b-256 b86fe724d6b5e80c5892e7345066b48bcff2b426a87f5c540666c86f51d6cd8f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page