PHPackages                             adrianlaraperez88/load-balancer - 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. [Database &amp; ORM](/categories/database)
4. /
5. adrianlaraperez88/load-balancer

ActiveLibrary[Database &amp; ORM](/categories/database)

adrianlaraperez88/load-balancer
===============================

Database-driven load balancer for Laravel applications

00PHPCI failing

Since Apr 20Pushed 1mo agoCompare

[ Source](https://github.com/adrianlaraperez88/load-balancer)[ Packagist](https://packagist.org/packages/adrianlaraperez88/load-balancer)[ RSS](/packages/adrianlaraperez88-load-balancer/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependenciesVersions (1)Used By (0)

Load Balancer
=============

[](#load-balancer)

A highly resilient, database-driven standalone Load Balancer package for Laravel 10 and 11 featuring Proxy and Native Redirect architectural modes, advanced state cachers, Enterprise-level scaling analytics, and strict SSRF security frameworks.

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

[](#installation)

Require the package via composer:

```
composer require adrianlaraperez88/load-balancer
```

Publish the package configuration files and database migrations:

```
php artisan vendor:publish --provider="Isg\LoadBalancer\LoadBalancerServiceProvider"
```

Run database migrations to generate up the internal rules &amp; metric tables:

```
php artisan migrate
```

Docker Simulated Staging
------------------------

[](#docker-simulated-staging)

This repository mathematically proves scale constraints via isolated Docker sandboxes protecting your native OS paths! We include a custom `PHP 8.3 CLI` container seamlessly wrapping Valkey Cache engines and three backend `nginx` simulated websites.

The testing cluster is isolated cleanly inside `tests/sandbox`. To boot the load balancer's Linux sandbox:

```
cd tests/sandbox
docker compose up -d
```

To run the automated PHPUnit verification models validating your extensions seamlessly:

```
docker compose exec app php vendor/bin/phpunit
```

Features &amp; Configuration
----------------------------

[](#features--configuration)

### 1. Proxies vs. Redirects (Modes)

[](#1-proxies-vs-redirects-modes)

By default, the load balancer operates in **Redirect Mode**. The software instantly issues an `HTTP 302` response pointing the client exactly to the loaded server location ensuring zero payload bandwidth footprint on your proxy machine.

If you don't expose your backing APIs and need your balancer to pipe the payload invisibly through local networks, you can flip over to **Proxy Mode**:

```
// config/load-balancer.php
'mode' => env('LOAD_BALANCER_MODE', 'proxy'),
```

Proxy mode safely handles all `X-Forwarded-*` headers, strips hop-by-hop blocks automatically, and intentionally turns off generic Guzzle decompressions to ensure `gzip` streams remain performant and don't break browsers!

### 2. High-Scale Analytics (Surviving Millions RPS)

[](#2-high-scale-analytics-surviving-millions-rps)

Writing metric analytics to databases or queues per request is catastrophic at extreme scale (1,000,000 req/sec).

To cleanly survive these waves, our asynchronous Metric Jobs trigger `dispatchAfterResponse()`, executing physically only after the user natively finishes unhooking their browser stream.

Additionally, you can activate Statistical Sampling. By tuning your `sample_rate`, the proxy utilizes lightweight mathematical probabilities (`mt_rand`) to log only specific fractions of your traffic. A value of `0.01` ensures exactly 1% of your traffic gets tracked, preventing queue IO bottlenecks whilst maintaining functionally perfect analytics.

```
// config/load-balancer.php
'logging' => [
    'enabled' => env('LOAD_BALANCER_LOGGING', true),
    'sample_rate' => env('LOAD_BALANCER_SAMPLE_RATE', 1.0), // Change to 0.01 for severe scales
],
```

### 3. IP Routing &amp; Sticky Sessions

[](#3-ip-routing--sticky-sessions)

Route consistency is vital for maintaining cache warmth inside cluster applications.

- **Sticky Sessions:** Setting `LOAD_BALANCER_STICKY_SESSIONS=true` internally switches the balancer to CRC32 map the incoming IP Address. 127.0.0.1 will constantly return the exact identical target upstream unless that upstream mathematically disables or dies!
- **`IpRule` Overrides:** Creating an `IpRule` array passing an IP logically binds that visitor to a specific `upstream_node_id`, bypassing standard strategies altogether for Admin or specialized Beta User handling!

### 4. Strict Security Limits &amp; WAF

[](#4-strict-security-limits--waf)

The `LoadBalancerManager` intercepts all Server-Side vulnerabilities implicitly:

1. Validates strict schema requirements, ensuring `file:///etc/passwd` injection rows are thrown cleanly with HTTP 500 status traps natively.
2. In Development or Local testing (`app()->environment('local')`), routing seamlessly translates local `http://` bindings.
3. Once the environment reads `production`, ANY target mappings lacking explicit TLS `https://` blocks hit our production safety trap.

**Native WAF Rate Limiting:**Built directly onto the proxy, a throttle automatically maps incoming connections. By default, it limits malicious scripts to `500` requests per minute per IP.

```
// config/load-balancer.php
'waf' => [
    'enabled' => env('LOAD_BALANCER_WAF_ENABLED', true),
    'limit' => env('LOAD_BALANCER_WAF_LIMIT', 500),
],
```

**Custom WAF Injection:**If your Host Laravel Application is already compiled with complex rate-limit arrays (e.g. infinite hits for admins overriding general traffic) inside your RouteServiceProvider `RateLimiter::for('api', ...)`:

Simply align the package perfectly without modifying routes or touching code by matching the array name: `LOAD_BALANCER_WAF_LIMITER=api`

The Load Balancer organically hooks into your native Laravel definitions dropping the internal WAF rules automatically!

### 5. Active Health Daemons &amp; Observability

[](#5-active-health-daemons--observability)

We provide mechanical command daemons replacing passive checks with autonomous background logic:

- Schedule `php artisan loadbalancer:health-check` in your Laravel `Kernel` to execute `->everyMinute()`. It pings all upstreams dynamically, auto-switching database `is_active` boundaries before your users ever hit timeouts.
- Need a Dashboard? Access `http://your-app.com/api/load-balancer/metrics` organically to retrieve structured JSON containing active clusters, aggregated request sums, and live latencies!

---

Included Strategies
-------------------

[](#included-strategies)

You completely dictate routing logic mathematically via `LOAD_BALANCER_DEFAULT_STRATEGY`:

- `round_robin` - Distribute predictably over all interchangeably weighed active models universally.
- `random` - Distributes completely arbitrarily.
- `weighted_random` - Favors upstream nodes mathematically matching larger `weight` parameters inside your Database strings.
- `active_passive` - Prioritizes `is_primary=true` nodes exclusively, relying heavily on backups solely if master caches collapse.
- `least_redirects` - Used exclusively alongside Redirect Mode—routes traffic seamlessly to whichever server owns the smallest dynamically tallying 24-hr usage metric to constantly normalize traffic spread organically.
- `adaptive_latency` - Realtime Smart Routing! Uses background statistics automatically sorting metrics to target the node possessing the absolute fastest Exponential Moving Average millisecond response!

Creating Custom Strategies
--------------------------

[](#creating-custom-strategies)

This component cleanly adheres to SOLID logic—you do not ever need to edit core package classes to invent new mapping targets! Simply add them to the array.

### 1. Build your Strategy

[](#1-build-your-strategy)

```
namespace App\LoadBalancing;

use Isg\LoadBalancer\Contracts\LoadBalancingStrategy;
use Illuminate\Support\Collection;
use Illuminate\Http\Request;
use Isg\LoadBalancer\Models\UpstreamNode;

class GeographicalStrategy implements LoadBalancingStrategy
{
    public function selectNode(Collection $nodes, ?Request $request = null): ?UpstreamNode
    {
        // Custom logic to parse origins natively via geoips and pick models here
        return $nodes->first();
    }
}
```

### 2. Append the Registry Map

[](#2-append-the-registry-map)

Register your logic inside the exported configurations associative list (`config/load-balancer.php`). Laravel's Service Container processes standard `make()` operations perfectly ensuring maximum compatibility!

```
'strategies' => [
    'round_robin'    => \Isg\LoadBalancer\Strategies\RoundRobinStrategy::class,
    'random'         => \Isg\LoadBalancer\Strategies\RandomStrategy::class,

    // Add your own strategies perfectly natively here!
    'geo_routing'    => \App\LoadBalancing\GeographicalStrategy::class,
],
```

Set `LOAD_BALANCER_DEFAULT_STRATEGY="geo_routing"` internally and watch the system fly beautifully!

###  Health Score

19

—

LowBetter than 10% of packages

Maintenance59

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity11

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/9151a4ecfa27c4fe417ccb560ed733c0296b323912c3a35b78e45f2b3a299d2a?d=identicon)[adrianlaraperez88](/maintainers/adrianlaraperez88)

---

Top Contributors

[![adrianlaraperez88](https://avatars.githubusercontent.com/u/19626181?v=4)](https://github.com/adrianlaraperez88 "adrianlaraperez88 (12 commits)")

### Embed Badge

![Health badge](/badges/adrianlaraperez88-load-balancer/health.svg)

```
[![Health](https://phpackages.com/badges/adrianlaraperez88-load-balancer/health.svg)](https://phpackages.com/packages/adrianlaraperez88-load-balancer)
```

###  Alternatives

[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k116.5M113](/packages/jdorn-sql-formatter)[propel/propel1

Propel is an open-source Object-Relational Mapping (ORM) for PHP5.

8361.6M87](/packages/propel-propel1)[mpociot/laravel-composite-key

Support composite keys in your laravel app.

3544.8k1](/packages/mpociot-laravel-composite-key)

PHPackages © 2026

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