Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Bijay Nayak

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
7 changes: 7 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@
show_signature: true
show_root_heading: true


::: fast_cache.MongoDBBackend
options:
show_source: true
show_signature: true
show_root_heading: true

## Backend Base Class

::: fast_cache.backends.backend.CacheBackend
19 changes: 13 additions & 6 deletions docs/backends.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ FastAPI Cachekit supports multiple cache backends, so you can choose the best fi

## Supported Backends

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

---

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

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

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

---

Expand Down
103 changes: 103 additions & 0 deletions docs/backends/mongodb.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# MongoDB Backend

The **MongoDBBackend** allows you to use a MongoDB database as a cache store for FastAPI Cachekit.
This backend is ideal when you want persistent, document-based caching, or when you already have a MongoDB database in your stack.
It supports automatic cache expiration using MongoDB’s TTL (Time-To-Live) indexes, making it easy to manage cache lifetimes efficiently.
---

## 🚀 Installation

Install FastAPI Cachekit with MongoDB support:

```
pip install fastapi-cachekit[mongodb]
```

Or with other tools:

- **uv**
```
uv add fastapi-cachekit[mongodb]
```
- **poetry**
```
poetry add fastapi-cachekit -E mongodb
```

---

## ⚙️ Setup with FastAPI

```python
from fast_cache import cache, MongoDBBackend

backend = MongoDBBackend(
uri="mongodb://user:password@localhost:27017/mydb",
namespace="myapp_cache"
)
cache.init_app(app, backend)
```

- `uri`: MongoDB connection string With All necessary Auth and Db in URL (required)
- `namespace`: Prefix for all cache keys (default: `"fastapi_cache"`)

---

## 🧑‍💻 Example Usage

```python
@app.get("/expensive")
@cache.cached(expire=120)
async def expensive_operation(x: int):
# This result will be cached in Postgres for 2 minutes
return {"result": x * 2}
```

---


# ⚡️ About MongoDB TTL Cache

> **This backend uses a MongoDB collection with a TTL (Time-To-Live) index for storing cache entries.**

- **TTL Indexes** in MongoDB automatically remove expired cache entries, so you don’t need to manage expiration manually.
- **Benefit:** Cache data is persistent across app and database restarts, and expired data is cleaned up automatically by MongoDB’s background process.
- **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.

**In summary:**
- Cache data is persistent and automatically expired, but there may be a short delay before expired entries are deleted.
- If you need instant removal of expired data, you should check expiration in your code (this backend does so).

---

## ⚠️ Tips & Limitations

- **Requires a running MongoDB server**.
- **Data is persistent across app and database restarts**.
- **Slightly slower than in-memory or Redis** for high-throughput caching, but great for persistence and document-based setups.
- **Best for apps already using MongoDB** or needing persistent, auto-expiring cache.
- **TTL index expiration is not instantaneous**; expired documents are removed in the background.

---
## 📝 How It Works

- Each cache entry is stored as a document with:
- `_id`: the cache key (optionally namespaced)
- `value`: the pickled cached value
- `expires_at`: epoch time when the entry should expire
- A TTL index is created on the `expires_at` field.
- Expired documents are deleted automatically by MongoDB’s TTL monitor.
- Expiration is also checked in code to avoid returning stale data.

---
## 🚦 When to Use
- You want persistent, document-based caching.
- You already have a MongoDB database in your stack.
- You want automatic cache expiration without manual cleanup.
---

## 🔗 See Also

- [Backends Overview](../backends.md)
- [API Reference](../api.md)
- [Usage Guide](../usage.md)
15 changes: 8 additions & 7 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ You can choose the backend that fits your needs, and switch between them with mi
## 🌟 Benefits

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

## 📦 Backends & Sync/Async Support

| Backend | Sync API | Async API | Install Extra |
|--------------------|:--------:|:---------:|----------------------|
| `InMemoryBackend` | ✅ | ✅ | _built-in_ |
| `RedisBackend` | ✅ | ✅ | `redis` |
| `PostgresBackend` | ✅ | ✅ | `postgres` |
| `MemcachedBackend` | ✅ | ✅ | `memcached` |
| Backend | Sync API | Async API | Install Extra |
|--------------------|:--------:|:---------:|---------------|
| `InMemoryBackend` | ✅ | ✅ | _built-in_ |
| `RedisBackend` | ✅ | ✅ | `redis` |
| `PostgresBackend` | ✅ | ✅ | `postgres` |
| `MemcachedBackend` | ✅ | ✅ | `memcached` |
| `MongoDB` | ✅ | ✅ | `mongodb` |

---

Expand Down
89 changes: 26 additions & 63 deletions docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,90 +9,53 @@ You can use **pip**, **uv**, or **poetry** and only install the backends you nee

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

### **pip**
```
pip install fastapi-cachekit
```

### **uv**
```
uv add fastapi-cachekit
```

### **poetry**
```
poetry add fastapi-cachekit
```
- **pip** `pip install fastapi-cachekit`
- **uv** `uv add fastapi-cachekit`
- **poetry** `poetry add fastapi-cachekit`

---

## 🔌 Optional Backends

You can install support for Redis, Postgres, or Memcached by specifying the appropriate "extra".
You can install support for Redis, Postgres, MongoDB or Memcached by specifying the appropriate "extra".

### **Redis Backend**

- **pip**
```
pip install fastapi-cachekit[redis]
```
- **uv**
```
uv add fastapi-cachekit[redis]
```
- **poetry**
```
poetry add fastapi-cachekit -E redis
```
- **pip** `pip install fastapi-cachekit[redis]`
- **uv** `uv add fastapi-cachekit[redis]`
- **poetry** `poetry add fastapi-cachekit -E redis`


### **Postgres Backend**

- **pip**
```
pip install fastapi-cachekit[postgres]
```
- **uv**
```
uv add fastapi-cachekit[postgres]
```
- **poetry**
```
poetry add fastapi-cachekit -E postgres
```
- **pip** `pip install fastapi-cachekit[postgres]`
- **uv** `uv add fastapi-cachekit[postgres]`
- **poetry** `poetry add fastapi-cachekit -E postgres`


### **Memcached Backend**

- **pip**
```
pip install fastapi-cachekit[memcached]
```
- **uv**
```
uv add fastapi-cachekit[memcached]
```
- **poetry**
```
poetry add fastapi-cachekit -E memcached
```
- **pip** `pip install fastapi-cachekit[memcached]`
- **uv** `uv add fastapi-cachekit[memcached]`
- **poetry** `poetry add fastapi-cachekit -E memcached`


### **MongoDB Backend**

- **pip** `pip install fastapi-cachekit[mongodb]`
- **uv** `uv add fastapi-cachekit[mongodb]`
- **poetry** `poetry add fastapi-cachekit -E mongodb`
---

## 🧩 Install All Backends

If you want to install all supported backends at once:

- **pip**
```
pip install fastapi-cachekit[all]
```
- **uv**
```
uv add fastapi-cachekit[all]
```
- **poetry**
```
poetry add fastapi-cachekit -E all
```
- **pip** `pip install fastapi-cachekit[all]`

- **uv** `uv add fastapi-cachekit[all]`

- **poetry** `poetry add fastapi-cachekit -E all `

---

Expand Down
3 changes: 2 additions & 1 deletion fast_cache/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
from .backends.memory import InMemoryBackend
from .backends.postgres import PostgresBackend
from .backends.memcached import MemcachedBackend
from .backends.mongodb import MongoDBBackend

__all__ = ["FastAPICache", "RedisBackend", "CacheBackend", "InMemoryBackend","PostgresBackend", "cache","MemcachedBackend" ]
__all__ = ["FastAPICache", "RedisBackend", "CacheBackend", "InMemoryBackend","PostgresBackend", "cache","MemcachedBackend", "MongoDBBackend" ]


# Create global cache instance
Expand Down
Loading