PHPackages                             aniki/api-rate-limiter - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. aniki/api-rate-limiter

ActiveLibrary[API Development](/categories/api)

aniki/api-rate-limiter
======================

Lightweight API rate limiter written in pure PHP with Redis

v1.0.0(5mo ago)00MITPHPPHP ^8.1

Since Jan 19Pushed 2mo agoCompare

[ Source](https://github.com/N1-San/api-rate-limiter)[ Packagist](https://packagist.org/packages/aniki/api-rate-limiter)[ RSS](/packages/aniki-api-rate-limiter/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (1)Versions (2)Used By (0)

API Rate Limiter (PHP + Redis)
==============================

[](#api-rate-limiter-php--redis)

A **framework-agnostic API rate limiter** written in plain PHP.

No Laravel. No Symfony. No magic.

Just **PHP, Redis, and well-defined boundaries**.

This project is designed for developers who care about:

- Predictable behavior under load
- Minimal setup and failure points
- Clear data models
- Easy self-hosting
- Open-source friendliness

If you can run PHP and Redis, you can run this.

---

Why this exists
---------------

[](#why-this-exists)

Most rate-limiting solutions are:

- Tightly coupled to frameworks
- Hidden behind service containers
- Difficult to reason about under failure
- Over-engineered for simple use cases

This project takes the opposite approach:

> **Explicit over implicit. Simple over clever. Boring over fragile.**

It is meant to be embedded:

- In internal APIs
- As an edge service in front of microservices
- As a standalone gateway
- As a learning reference for real-world system design

---

Features
--------

[](#features)

- ✅ Fixed Window rate limiting (Redis-backed)
- ✅ API key–based authentication
- ✅ Redis TTL–driven expiry (no cron jobs)
- ✅ Framework-agnostic middleware pipeline
- ✅ Predictable Redis key schema
- ✅ Zero runtime dependencies beyond Redis
- ✅ Works with PHP built-in server, Nginx, Apache, or Docker

Planned:

- Sliding Window / Token Bucket
- Per-route limits
- Burst control
- Distributed Redis support
- Metrics export (Prometheus)

---

Architecture (High-Level)
-------------------------

[](#architecture-high-level)

```
┌────────────┐     ┌──────────────────┐     ┌──────────────┐
│ HTTP Client│ ──▶ │ RateLimitMiddleware│ ──▶ │ Application  │
└────────────┘     └──────────────────┘     └──────────────┘
                           │
                           ▼
                    ┌──────────────┐
                    │ Redis        │
                    │ (Atomic ops) │
                    └──────────────┘

```

### Design principles

[](#design-principles)

- **Stateless PHP** – all state lives in Redis
- **Atomic Redis operations** – correctness under concurrency
- **Explicit failure modes** – no silent fallbacks
- **Readable over clever** – optimized last, understood first

---

Redis Schema
------------

[](#redis-schema)

All keys are namespaced and deterministic.

```
rl:{api_key}:{window_start}

```

Example:

```
rl:test-key-123:1705651200

```

- Value: request count (integer)
- TTL: window size (seconds)

Redis is the source of truth.

No local caches. No sync problems.

---

Project Structure
-----------------

[](#project-structure)

```
api-rate-limiter/
├── public/
│   └── index.php        # Front controller
├── src/
│   ├── Http/
│   │   └── Middleware/
│   │       └── RateLimitMiddleware.php
│   ├── Infrastructure/
│   │   └── RedisClient.php
│   ├── RateLimiting/
│   │   └── FixedWindowLimiter.php
│   ├── Kernel.php       # Middleware pipeline
│   └── Response.php
├── composer.json
└── README.md

```

Nothing hidden.

If you delete a file, you know exactly what broke.

---

Installation
------------

[](#installation)

### Requirements

[](#requirements)

- PHP **8.1+** (8.3 recommended)
- Redis **6+**
- Composer

### Install dependencies

[](#install-dependencies)

```
composer install

```

### Configure Redis

[](#configure-redis)

Edit your environment or config:

```
REDIS_HOST=127.0.0.1
REDIS_PORT=6379

```

---

Running locally
---------------

[](#running-locally)

Using PHP’s built-in server:

```
php -S localhost:8888 -t public

```

Test:

```
curl -H "X-API-Key: test-key-123" http://localhost:8888

```

---

API Key Handling
----------------

[](#api-key-handling)

This project **does not** manage API key storage for you.

That is intentional.

You can:

- Hardcode keys (for internal services)
- Load from env
- Validate against Redis / DB
- Plug into an external auth service

The middleware only enforces **rate limits**, not identity semantics.

---

Failure Modes (Explicit by Design)
----------------------------------

[](#failure-modes-explicit-by-design)

ConditionResponseMissing API key`401 Unauthorized`Invalid API key`401 Unauthorized`Rate limit exceeded`429 Too Many Requests`Redis unavailableFail-fast (configurable)No silent degradation.

If Redis is down, you *should know*.

---

Why Fixed Window?
-----------------

[](#why-fixed-window)

Fixed Window is:

- Easy to reason about
- Cheap in Redis
- Deterministic

Yes, it allows bursts at window edges.

That tradeoff is **explicit**, not accidental.

More advanced algorithms can be layered on later.

---

Philosophy
----------

[](#philosophy)

This project is intentionally boring.

- No service containers
- No annotations
- No magic globals

Just code you can:

- Read in one sitting
- Debug with `var_dump`
- Trust in production

---

Who this is for
---------------

[](#who-this-is-for)

- Backend engineers who want control
- Teams building internal platforms
- Developers learning real system design
- People tired of framework lock-in

If you want batteries included, this is not for you.

If you want **understanding**, it is.

---

License
-------

[](#license)

MIT

Use it. Break it. Fork it. Improve it.

---

Final note
----------

[](#final-note)

If you are reading this README and thinking:

> “This feels like something I could actually run in production”

That is the goal.

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance79

Regular maintenance activity

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

165d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/33519431?v=4)[Aniki](/maintainers/N1-San)[@N1-San](https://github.com/N1-San)

---

Top Contributors

[![N1-San](https://avatars.githubusercontent.com/u/33519431?v=4)](https://github.com/N1-San "N1-San (5 commits)")

### Embed Badge

![Health badge](/badges/aniki-api-rate-limiter/health.svg)

```
[![Health](https://phpackages.com/badges/aniki-api-rate-limiter/health.svg)](https://phpackages.com/packages/aniki-api-rate-limiter)
```

###  Alternatives

[bagisto/bagisto

Bagisto Laravel E-Commerce

27.6k172.1k9](/packages/bagisto-bagisto)[unopim/unopim

UnoPim Laravel PIM

10.5k2.4k](/packages/unopim-unopim)[oro/platform

Business Application Platform (BAP)

645143.5k115](/packages/oro-platform)[concrete5/core

Concrete core subtree split

20166.1k52](/packages/concrete5-core)[stfalcon-studio/api-bundle

Base classes and helper services to build API application via Symfony.

1035.6k](/packages/stfalcon-studio-api-bundle)[lion/bundle

Lion-framework configuration and initialization package

122.3k4](/packages/lion-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
