|
| 1 | +# MongoDB Backend |
| 2 | + |
| 3 | +The **MongoDBBackend** allows you to use a MongoDB database as a cache store for FastAPI Cachekit. |
| 4 | +This backend is ideal when you want persistent, document-based caching, or when you already have a MongoDB database in your stack. |
| 5 | +It supports automatic cache expiration using MongoDB’s TTL (Time-To-Live) indexes, making it easy to manage cache lifetimes efficiently. |
| 6 | +--- |
| 7 | + |
| 8 | +## 🚀 Installation |
| 9 | + |
| 10 | +Install FastAPI Cachekit with MongoDB support: |
| 11 | + |
| 12 | +``` |
| 13 | +pip install fastapi-cachekit[mongodb] |
| 14 | +``` |
| 15 | + |
| 16 | +Or with other tools: |
| 17 | + |
| 18 | +- **uv** |
| 19 | +``` |
| 20 | +uv add fastapi-cachekit[mongodb] |
| 21 | +``` |
| 22 | +- **poetry** |
| 23 | +``` |
| 24 | +poetry add fastapi-cachekit -E mongodb |
| 25 | +``` |
| 26 | + |
| 27 | +--- |
| 28 | + |
| 29 | +## ⚙️ Setup with FastAPI |
| 30 | + |
| 31 | +```python |
| 32 | +from fast_cache import cache, MongoDBBackend |
| 33 | + |
| 34 | +backend = MongoDBBackend( |
| 35 | + uri="mongodb://user:password@localhost:27017/mydb", |
| 36 | + namespace="myapp_cache" |
| 37 | +) |
| 38 | +cache.init_app(app, backend) |
| 39 | +``` |
| 40 | + |
| 41 | +- `uri`: MongoDB connection string With All necessary Auth and Db in URL (required) |
| 42 | +- `namespace`: Prefix for all cache keys (default: `"fastapi_cache"`) |
| 43 | + |
| 44 | +--- |
| 45 | + |
| 46 | +## 🧑💻 Example Usage |
| 47 | + |
| 48 | +```python |
| 49 | +@app.get("/expensive") |
| 50 | +@cache.cached(expire=120) |
| 51 | +async def expensive_operation(x: int): |
| 52 | + # This result will be cached in Postgres for 2 minutes |
| 53 | + return {"result": x * 2} |
| 54 | +``` |
| 55 | + |
| 56 | +--- |
| 57 | + |
| 58 | + |
| 59 | +# ⚡️ About MongoDB TTL Cache |
| 60 | + |
| 61 | +> **This backend uses a MongoDB collection with a TTL (Time-To-Live) index for storing cache entries.** |
| 62 | +
|
| 63 | +- **TTL Indexes** in MongoDB automatically remove expired cache entries, so you don’t need to manage expiration manually. |
| 64 | +- **Benefit:** Cache data is persistent across app and database restarts, and expired data is cleaned up automatically by MongoDB’s background process. |
| 65 | +- **Drawback:** Expired documents may not be deleted immediately (MongoDB’s TTL monitor runs every 60 seconds by default), so there may be a short delay before expired cache entries are removed. |
| 66 | + |
| 67 | +**In summary:** |
| 68 | +- Cache data is persistent and automatically expired, but there may be a short delay before expired entries are deleted. |
| 69 | +- If you need instant removal of expired data, you should check expiration in your code (this backend does so). |
| 70 | + |
| 71 | +--- |
| 72 | + |
| 73 | +## ⚠️ Tips & Limitations |
| 74 | + |
| 75 | +- **Requires a running MongoDB server**. |
| 76 | +- **Data is persistent across app and database restarts**. |
| 77 | +- **Slightly slower than in-memory or Redis** for high-throughput caching, but great for persistence and document-based setups. |
| 78 | +- **Best for apps already using MongoDB** or needing persistent, auto-expiring cache. |
| 79 | +- **TTL index expiration is not instantaneous**; expired documents are removed in the background. |
| 80 | + |
| 81 | +--- |
| 82 | +## 📝 How It Works |
| 83 | + |
| 84 | +- Each cache entry is stored as a document with: |
| 85 | + - `_id`: the cache key (optionally namespaced) |
| 86 | + - `value`: the pickled cached value |
| 87 | + - `expires_at`: epoch time when the entry should expire |
| 88 | +- A TTL index is created on the `expires_at` field. |
| 89 | +- Expired documents are deleted automatically by MongoDB’s TTL monitor. |
| 90 | +- Expiration is also checked in code to avoid returning stale data. |
| 91 | + |
| 92 | +--- |
| 93 | +## 🚦 When to Use |
| 94 | +- You want persistent, document-based caching. |
| 95 | +- You already have a MongoDB database in your stack. |
| 96 | +- You want automatic cache expiration without manual cleanup. |
| 97 | +--- |
| 98 | + |
| 99 | +## 🔗 See Also |
| 100 | + |
| 101 | +- [Backends Overview](../backends.md) |
| 102 | +- [API Reference](../api.md) |
| 103 | +- [Usage Guide](../usage.md) |
0 commit comments