Prevent Spring Boot Cache Penetration with a Single @BloomCheck Annotation
This article introduces the bloomfilter-spring-boot-starter library that provides declarative @BloomCheck and @BloomAdd annotations to prevent cache penetration in Spring Boot 3.5+, supporting both in-memory and Redis backends with fail-open safety, keyed SipHash, Micrometer metrics, and scheduled filter rebuilds.
Reading font
1. Introduction
In high-concurrency scenarios, querying non-existent IDs causes cache penetration: Redis misses, requests hit the database directly, and the database cannot handle the load. Bloom filters can help, but implementing hashing, resizing, pre-warming, and distributed sharing manually leads to heavy code.
This article presents bloomfilter-spring-boot-starter (version 0.4.0), an open-source component that wraps Bloom filters into annotations for Spring Boot 3.5 and 4. A single @BloomCheck annotation short-circuits lookups for definitely absent keys, preventing invalid requests from reaching the database.
Key Features
Single dependency, few lines of YAML. Supports in-memory or Redis backend, switchable via configuration.
Annotations: @BloomCheck short-circuits lookups for definitely absent keys; @BloomAdd keeps the filter updated.
Safety by design: never returns a wrong "not found". Backend outages, lost writes, and warm-up fall back to "might contain".
Secure hashing: keyed SipHash prevents hash-flooding attacks.
Observability: Micrometer metrics (including measured false-positive rate) and /actuator/bloomfilters endpoint.
2. Practical Examples
2.1 Environment Setup
Environment: Spring Boot 3.5.0
2.2 Dependency
<dependency>
<groupId>io.github.ncibioussama</groupId>
<artifactId>bloomfilter-spring-boot-starter</artifactId>
<version>0.4.0</version>
</dependency>2.3 Basic Configuration
bloom:
filters:
users:
# sized for 1M keys
expected-insertions: 1000000
# 1% → 1.14 MiB, 7 hash functions
false-positive-rate: 0.012.4 Basic Usage
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
// If the ID was never added, returns Optional.empty() without touching the database.
@BloomCheck(filter = "users", key = "#id")
public Optional<User> findById(Long id) {
return userRepository.findById(id);
}
// Throws BloomFilterMissException if absent
@BloomCheck(filter = "users", key = "#email", onMiss = OnMiss.THROW)
public User getByEmail(String email) {
// ...
}
@BloomAdd(filter = "users", key = "#result.id")
public User create(CreateUserRequest request) {
// ...
}
}Programmatic access is also available:
private final BloomFilterRegistry registry;
BloomFilter users = registry.get("users");
if (!users.mightContain(id)) {
return Optional.empty();
}Key comparison uses canonical forms, so 42, 42L, and "42" are treated as the same key. Supported key types: strings, integers, BigDecimal, UUID, enums, and byte[].
2.5 Initial Data Loading
Implement BloomFilterLoader to pre-populate the filter at startup:
@Component
public class UserIdLoader implements BloomFilterLoader {
private final UserRepository userRepository;
public UserIdLoader(UserRepository userRepository) {
this.userRepository = userRepository;
}
public String filterName() {
return "users";
}
@Transactional(readOnly = true)
public void load(BloomFilter filter) {
try (Stream<Long> ids = userRepository.streamAllIds()) {
filter.putAll((Iterable<Long>) ids::iterator);
}
}
}The component automatically invokes load based on the configured filterName; no manual call is needed.
2.6 Cross-Instance Filter Sharing (Redis Backend)
Add the Redis starter dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>Configuration:
spring:
data:
redis:
client-type: lettuce
host: localhost
port: 6379
password:
database: 0
bloom:
default-backend: redis
security:
# length ≥ 16 chars, kept consistent across restarts
secret: ${BLOOM_SECRET}
redis:
key-prefix: "bloom:app:"
filters:
users:
expected-insertions: 10000000
false-positive-rate: 0.001
# or 'throw'
failure-mode: fail-openEach check or insert is an atomic Lua call. With default warm-up.mode=if-empty, the shared filter loads only once: subsequent instances skip loading only after the current load completes, never while another instance is still loading.
2.7 Scheduled Rebuild
Bloom filters cannot delete keys, so deleted rows remain marked "might exist", gradually filling the filter. Rebuild reloads every key from the BloomFilterLoader into a new filter and swaps it atomically:
bloom:
filters:
users:
# every night at 3 AM
rebuild-cron: "0 0 3 * * *"No wrong answers during rebuild. The current filter keeps serving checks. Keys added during rebuild are written to both filters, so nothing is lost on swap.
Redis: the new bitmap is built under a :next key and swapped with a single atomic RENAME; all instances switch at the same instant. A Redis lock ensures only one instance rebuilds. If rebuild exceeds bloom.rebuild.timeout, it is cancelled to avoid lost-write risk.
Self-healing: filters in DEGRADED state (due to lost writes or Redis unavailable at startup) automatically rebuild every bloom.rebuild.recovery-interval until successful, then resume answering queries.
On-demand rebuild: call rebuilder.rebuild("users") (inject BloomFilterRebuilder), or POST /actuator/bloomfilters/users with bloom.rebuild.endpoint-enabled=true (secure Actuator first).
3. Security Management
The article provides a threat-mitigation mapping:
Hash-flooding (attacker crafts keys to fill filter) : Keyed SipHash-2-4. In-memory filters use a random key; Redis uses bloom.security.secret.
Wrong "not found" when Redis is down or writes are lost : Fail-open, then enter bypass mode ( DEGRADED) until auto-rebuild succeeds.
Wrong "not found" during startup : Bypass checks until loader finishes; shared filters are skipped only after fully loaded.
Wrong "not found" during rebuild : Old filter continues serving until atomic swap; concurrent writes go to both filters.
Rebuild endpoint abused to load database : Rebuild, pause, and resume endpoints disabled by default unless bloom.rebuild.endpoint-enabled=true; only one rebuild per filter at a time.
Wrong "not found" for rows written outside the app : Pause filters during migrations and imports.
Misconfiguration causing OOM : bloom.max-bits-per-filter (default 512 MiB).
Oversized keys (CPU drain, or filter shutdown) : Keys exceeding bloom.max-key-bytes (default 4096) are never stored and always answer "might contain", so they reach the DB — no error, no filter degradation, no rebuild failure.
Injection via key expressions : SpEL expressions come only from annotations; parameter values are always treated as data, never evaluated.
Key leakage (emails, tokens) : Keys never appear in logs, exceptions, metrics, or endpoints.
Changing shared filter size or key : Redis keys embed a config fingerprint, so a new empty filter is used and reloaded.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.
Published
AI-assisted summary