Skip to content

Commit 5972091

Browse files
authored
Merge pull request #1 from devbijay/dev
feat: add MongoDB backend and tests
2 parents 4245b0c + 2182838 commit 5972091

14 files changed

Lines changed: 674 additions & 80 deletions

File tree

LICENSE.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2025 Bijay Nayak
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

docs/api.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,13 @@
3232
show_signature: true
3333
show_root_heading: true
3434

35+
36+
::: fast_cache.MongoDBBackend
37+
options:
38+
show_source: true
39+
show_signature: true
40+
show_root_heading: true
41+
3542
## Backend Base Class
3643

3744
::: fast_cache.backends.backend.CacheBackend

docs/backends.md

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,13 @@ FastAPI Cachekit supports multiple cache backends, so you can choose the best fi
66

77
## Supported Backends
88

9-
| Backend | Description | Best For | Docs |
10-
|--------------------|--------------------------------------------------|-------------------------|---------------------|
11-
| InMemoryBackend | Stores cache in the app’s memory (LRU support) | Development, testing | [In-Memory](backends/in_memory.md) |
12-
| RedisBackend | Uses Redis for distributed, production caching | Production, scaling | [Redis](backends/redis.md) |
13-
| PostgresBackend | Uses PostgreSQL for persistent SQL-based caching | Data persistence, SQL | [Postgres](backends/postgres.md) |
14-
| MemcachedBackend | Uses Memcached for high-speed distributed caching | High-speed, stateless | [Memcached](backends/memcached.md) |
9+
| Backend | Description | Best For | Docs |
10+
|------------------|--------------------------------------------------|-------------------------|------------------------------------|
11+
| InMemoryBackend | Stores cache in the app’s memory (LRU support) | Development, testing | [In-Memory](backends/in_memory.md) |
12+
| RedisBackend | Uses Redis for distributed, production caching | Production, scaling | [Redis](backends/redis.md) |
13+
| PostgresBackend | Uses PostgreSQL for persistent SQL-based caching | Data persistence, SQL | [Postgres](backends/postgres.md) |
14+
| MemcachedBackend | Uses Memcached for high-speed distributed caching | High-speed, stateless | [Memcached](backends/memcached.md) |
15+
| MongoDBBackend | Uses Memcached for high-speed distributed caching | High-speed, stateless | [MongoDB](backends/mongodb.md) |
1516

1617
---
1718

@@ -37,6 +38,11 @@ FastAPI Cachekit supports multiple cache backends, so you can choose the best fi
3738
- 🔴 No persistence (data lost on restart).
3839
- 🔴 No built-in authentication by default.
3940

41+
- **MongoDBBackend**
42+
- 🟢 Persistent storage (data survives restarts).
43+
- 🟢 Built-in TTL index for automatic cache expiration.
44+
- 🟢 Supports authentication and access control.
45+
- 🟡 Slower than in-memory caches (e.g., Memcached).
4046
---
4147

4248
## Installation for Each Backend
@@ -51,6 +57,7 @@ See the [Installation Guide](installation.md) for details on installing optional
5157
- [Redis Backend](backends/redis.md)
5258
- [Postgres Backend](backends/postgres.md)
5359
- [Memcached Backend](backends/memcached.md)
60+
- [MongoDB Backend](backends/mongodb.md)
5461

5562
---
5663

docs/backends/mongodb.md

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
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)

docs/index.md

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ You can choose the backend that fits your needs, and switch between them with mi
2222
## 🌟 Benefits
2323

2424
- **Plug-and-play:** Add caching to any FastAPI endpoint with a simple decorator.
25-
- **Multiple backends:** Use in-memory, Redis, Postgres, or Memcached—swap backends with a single line of code.
25+
- **Multiple backends:** Use in-memory, Redis, Postgres, or Memcache. Swap backends with a single line of code.
2626
- **Sync & Async support:** Works seamlessly with both synchronous and asynchronous FastAPI endpoints.
2727
- **Performance:** Reduce database load, speed up API responses, and improve scalability.
2828
- **Optional dependencies:** Only install the backend you need, keeping your project lightweight.
@@ -33,12 +33,13 @@ You can choose the backend that fits your needs, and switch between them with mi
3333

3434
## 📦 Backends & Sync/Async Support
3535

36-
| Backend | Sync API | Async API | Install Extra |
37-
|--------------------|:--------:|:---------:|----------------------|
38-
| `InMemoryBackend` ||| _built-in_ |
39-
| `RedisBackend` ||| `redis` |
40-
| `PostgresBackend` ||| `postgres` |
41-
| `MemcachedBackend` ||| `memcached` |
36+
| Backend | Sync API | Async API | Install Extra |
37+
|--------------------|:--------:|:---------:|---------------|
38+
| `InMemoryBackend` ||| _built-in_ |
39+
| `RedisBackend` ||| `redis` |
40+
| `PostgresBackend` ||| `postgres` |
41+
| `MemcachedBackend` ||| `memcached` |
42+
| `MongoDB` ||| `mongodb` |
4243

4344
---
4445

docs/installation.md

Lines changed: 26 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -9,90 +9,53 @@ You can use **pip**, **uv**, or **poetry** and only install the backends you nee
99

1010
Install the core package (in-memory backend only):
1111

12-
### **pip**
13-
```
14-
pip install fastapi-cachekit
15-
```
16-
17-
### **uv**
18-
```
19-
uv add fastapi-cachekit
20-
```
21-
22-
### **poetry**
23-
```
24-
poetry add fastapi-cachekit
25-
```
12+
- **pip** `pip install fastapi-cachekit`
13+
- **uv** `uv add fastapi-cachekit`
14+
- **poetry** `poetry add fastapi-cachekit`
2615

2716
---
2817

2918
## 🔌 Optional Backends
3019

31-
You can install support for Redis, Postgres, or Memcached by specifying the appropriate "extra".
20+
You can install support for Redis, Postgres, MongoDB or Memcached by specifying the appropriate "extra".
3221

3322
### **Redis Backend**
3423

35-
- **pip**
36-
```
37-
pip install fastapi-cachekit[redis]
38-
```
39-
- **uv**
40-
```
41-
uv add fastapi-cachekit[redis]
42-
```
43-
- **poetry**
44-
```
45-
poetry add fastapi-cachekit -E redis
46-
```
24+
- **pip** `pip install fastapi-cachekit[redis]`
25+
- **uv** `uv add fastapi-cachekit[redis]`
26+
- **poetry** `poetry add fastapi-cachekit -E redis`
27+
4728

4829
### **Postgres Backend**
4930

50-
- **pip**
51-
```
52-
pip install fastapi-cachekit[postgres]
53-
```
54-
- **uv**
55-
```
56-
uv add fastapi-cachekit[postgres]
57-
```
58-
- **poetry**
59-
```
60-
poetry add fastapi-cachekit -E postgres
61-
```
31+
- **pip** `pip install fastapi-cachekit[postgres]`
32+
- **uv** `uv add fastapi-cachekit[postgres]`
33+
- **poetry** `poetry add fastapi-cachekit -E postgres`
34+
6235

6336
### **Memcached Backend**
6437

65-
- **pip**
66-
```
67-
pip install fastapi-cachekit[memcached]
68-
```
69-
- **uv**
70-
```
71-
uv add fastapi-cachekit[memcached]
72-
```
73-
- **poetry**
74-
```
75-
poetry add fastapi-cachekit -E memcached
76-
```
38+
- **pip** `pip install fastapi-cachekit[memcached]`
39+
- **uv** `uv add fastapi-cachekit[memcached]`
40+
- **poetry** `poetry add fastapi-cachekit -E memcached`
41+
7742

43+
### **MongoDB Backend**
44+
45+
- **pip** `pip install fastapi-cachekit[mongodb]`
46+
- **uv** `uv add fastapi-cachekit[mongodb]`
47+
- **poetry** `poetry add fastapi-cachekit -E mongodb`
7848
---
7949

8050
## 🧩 Install All Backends
8151

8252
If you want to install all supported backends at once:
8353

84-
- **pip**
85-
```
86-
pip install fastapi-cachekit[all]
87-
```
88-
- **uv**
89-
```
90-
uv add fastapi-cachekit[all]
91-
```
92-
- **poetry**
93-
```
94-
poetry add fastapi-cachekit -E all
95-
```
54+
- **pip** `pip install fastapi-cachekit[all]`
55+
56+
- **uv** `uv add fastapi-cachekit[all]`
57+
58+
- **poetry** `poetry add fastapi-cachekit -E all `
9659

9760
---
9861

fast_cache/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@
55
from .backends.memory import InMemoryBackend
66
from .backends.postgres import PostgresBackend
77
from .backends.memcached import MemcachedBackend
8+
from .backends.mongodb import MongoDBBackend
89

9-
__all__ = ["FastAPICache", "RedisBackend", "CacheBackend", "InMemoryBackend","PostgresBackend", "cache","MemcachedBackend" ]
10+
__all__ = ["FastAPICache", "RedisBackend", "CacheBackend", "InMemoryBackend","PostgresBackend", "cache","MemcachedBackend", "MongoDBBackend" ]
1011

1112

1213
# Create global cache instance

0 commit comments

Comments
 (0)