Overview
The MongoDB persistence adapter provides distributed locks, circuit breaker state management, caching, and checkpoint support using MongoDB as the backend. It leverages MongoDB’s native TTL indexes for automatic expiration and unique indexes for lock acquisition.Installation
Features
- Distributed Locks: TTL-based locks with automatic expiration via MongoDB TTL indexes
- Circuit Breaker State: Persistent failure tracking with document storage
- Caching: High-performance cache with native TTL support
- Checkpoints: Full checkpoint support for task recovery
- Idempotency: Prevent duplicate operations (via
MongoDBIdempotencyAdapter) - Auto Indexing: Automatic index creation on connect
- No Manual Cleanup: MongoDB TTL indexes handle expiration automatically
Basic Usage
Configuration
MongoDB database instance
Configuration options
Collections and Indexes
The adapter automatically creates the following collections and indexes onconnect():
go_goscope_locks
- Unique Index:
{ key: 1 } - TTL Index:
{ expiresAt: 1 }withexpireAfterSeconds: 0
go_goscope_circuit
- Unique Index:
{ key: 1 }
go_goscope_cache
- Unique Index:
{ key: 1 } - TTL Index:
{ expiresAt: 1 }withexpireAfterSeconds: 0
go_goscope_checkpoints
- Unique Index:
{ taskId: 1, sequence: 1 } - Index:
{ taskId: 1 }
Lock Provider Methods
acquire(key, ttl, owner?)
Acquires a distributed lock using MongoDB’s unique index constraint. Automatically expires via TTL index.Lock identifier
Time-to-live in milliseconds
Optional lock owner identifier (auto-generated if not provided)
Promise<LockHandle | null> - Lock handle or null if already locked (duplicate key error)
extend(key, ttl, owner)
Extends the TTL of an existing lock by updating theexpiresAt field.
Lock identifier
New time-to-live in milliseconds
Lock owner identifier
Promise<boolean> - True if extended successfully
forceRelease(key)
Forces release of a lock regardless of owner.Lock identifier
Cache Provider Methods
get(key)
Retrieves a cached value. Automatically checks expiration (MongoDB TTL is eventually consistent).Cache key
Promise<T | null> - Cached value or null if not found/expired
set(key, value, ttl?)
Stores a value in the cache.Cache key
Value to cache (stored as-is, no JSON serialization required)
Time-to-live in milliseconds (optional)
delete(key)
Removes a cached value.Cache key
has(key)
Checks if a key exists in the cache.Cache key
Promise<boolean>
clear()
Clears all cached values (respects key prefix if set).keys(pattern?)
Lists all cache keys matching an optional pattern.Optional regex pattern (e.g.,
'user:.*')Promise<string[]> - Array of matching keys
Circuit Breaker Methods
getState(key)
Retrieves circuit breaker state.Circuit breaker identifier
Promise<CircuitBreakerPersistedState | null>
setState(key, state)
Updates circuit breaker state.Circuit breaker identifier
New state (state, failureCount, lastFailureTime, lastSuccessTime)
recordFailure(key, maxFailures)
Records a failure and potentially opens the circuit.Circuit breaker identifier
Maximum failures before opening circuit
Promise<number> - Current failure count
recordSuccess(key)
Records a success and closes the circuit.Circuit breaker identifier
Connection Example
MongoDB Atlas Example
Best Practices
Lock acquisition uses MongoDB’s unique index constraint for atomic operations. Duplicate key errors (code 11000) indicate the lock is already held.
Performance Considerations
- TTL indexes automatically clean up expired documents
- Unique indexes provide atomic lock acquisition
- Connection pooling is handled by the MongoClient
- Use compound indexes for checkpoint queries on large datasets
- Consider sharding for very high lock contention scenarios
Document Structure Examples
Lock Document
Circuit Breaker Document
Cache Document
Related
Redis Adapter
Redis-based persistence
DynamoDB Adapter
DynamoDB-based persistence