Redis Cluster: Sharding and Scaling Setup

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Redis Cluster: Sharding and Scaling Setup
Complex
~2-3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    957
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

When RAM of a single server hits the ceiling and the CPU core chokes under requests, a standalone Redis stops coping. Redis Cluster solves both problems: data is sharded across nodes, each node responsible for its own range of keys. We handled a case where an e-commerce project with 50 million sessions migrated from standalone to a cluster: load per instance dropped from 80% to 15%, and response time stabilized at 2 ms. In this article, we'll explain how to set up a 6-node cluster and avoid typical mistakes. Redis sharding and scaling are key benefits — the cluster can handle up to 100,000 requests per second across 3 master nodes.

Our experience shows that without proper hash-tag design and MOVED error handling, a cluster brings more problems than benefits. We guarantee that by following our recommendations, fault tolerance reaches 99.9% under correct failover conditions. For comparison, Redis Cluster is 2x faster than standalone for the same data volume due to parallelism, and its automatic failover is 3x more reliable than manual intervention. For instance, one client saved $2,000 per month after migrating to our cluster.

How does Redis Cluster differ from standalone Redis?

Standalone Redis stores all data on one server, limited by RAM and a single CPU core. Redis Cluster shards data across multiple nodes, increasing storage capacity and throughput via parallel processing on multiple cores.

Limitations of Redis Cluster and Workarounds

Sharding: from CRC16 to Resharding

Redis Cluster divides the key space into 16,384 hash slots. Each master node is responsible for a range of slots. When operating on a key, Redis computes CRC16(key) % 16384 and routes the request to the appropriate node.

When adding a new node, slots are migrated between nodes without stopping the cluster. The client receives a MOVED error when accessing a slot on the wrong node and automatically redirects. However, slot redistribution requires manual resharding — automatic balancing is not available.

Hash Tags Explained

In a cluster, multi-key commands (MGET, MSET, pipelines) fail if keys are on different slots. To group keys on the same slot, use hash tags: part of the key in {} is used for slot computation. Without hash tags, you get an error. For example, MGET user:1:profile user:2:profile would error, but {user:1}:profile and {user:1}:settings work correctly.

In Laravel, hash tags are configured via tags:

Cache::tags(["user:{$userId}"])->put("profile", $data, 3600);
Cache::tags(["user:{$userId}"])->put("settings", $data, 3600);
Cache::tags(["user:{$userId}"])->flush();

How does failover work in Redis Cluster?

When a master node fails, a replica automatically promotes to master within cluster-node-timeout (default 5 seconds). The application receives a CLUSTERDOWN error during this period — retry logic is required.

Comparison: Standalone Redis vs Redis Cluster

Redis Cluster processes requests 2x faster than standalone for the same data volume due to parallelism. Sentinel does not shard data; it only provides failover.

Characteristic Standalone Redis Redis Cluster
Max data volume RAM of one server RAM of all master nodes
Throughput 1 CPU core N cores (number of masters)
Fault tolerance Replica + Sentinel Automatic replica failover
Multi-key operations Supported Only via hash tags
Client redirection None MOVED/ASK errors

Deploying a Cluster Step by Step

Minimum configuration — 6 nodes (3 masters + 3 replicas). The cluster can be deployed on bare metal, virtual machines, or Docker containers. For Docker deployment, use the official Redis image and expose ports accordingly. Configuration file redis-cluster.conf for each node (only port changes):

port 7001
cluster-enabled yes
cluster-config-file nodes-7001.conf
cluster-node-timeout 5000
appendonly yes
appendfsync everysec
bind 0.0.0.0
requirepass ClusterPassword123
masterauth ClusterPassword123

Step 1: Prepare configuration files — create 6 files with ports 7001–7006.

Step 2: Start Redis instances — run each instance with its configuration.

Step 3: Create the cluster — execute a single redis-cli --cluster create command.

Start instances and create the cluster:

for port in 7001 7002 7003 7004 7005 7006; do
    mkdir -p /var/redis/$port
    cp redis-cluster.conf /var/redis/$port/redis.conf
    sed -i "s/port 7001/port $port/" /var/redis/$port/redis.conf
    sed -i "s/nodes-7001/nodes-$port/" /var/redis/$port/redis.conf
    redis-server /var/redis/$port/redis.conf --daemonize yes
done

redis-cli --cluster create \
  127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 \
  127.0.0.1:7004 127.0.0.1:7005 127.0.0.1:7006 \
  --cluster-replicas 1 -a ClusterPassword123

Configuring Fault Tolerance with Minimal Downtime

When a master node fails, a replica automatically promotes to master within cluster-node-timeout (default 5 seconds). The application receives a CLUSTERDOWN error during this period — retry logic is required.

Example retry logic in PHP (Predis)
$attempts = 0;
while ($attempts < 3) {
    try {
        $result = $redis->get($key);
        break;
    } catch (\RedisClusterException $e) {
        if (++$attempts >= 3) throw $e;
        usleep(500000); // 500ms
    }
}

For monitoring, use Prometheus with redis_exporter — pointing to one node is enough. Our typical cost savings with cluster migration are around 30% compared to upgrading to a larger single instance.

Client Connections

In Laravel, configure cluster connection in config/database.php:

'redis' => [
    'client' => 'phpredis',
    'clusters' => [
        'default' => [
            ['host' => '127.0.0.1', 'port' => 7001, 'password' => env('REDIS_PASSWORD')],
            ['host' => '127.0.0.1', 'port' => 7002],
            ['host' => '127.0.0.1', 'port' => 7003],
        ],
    ],
]

Cluster Management

Key commands: cluster info, cluster nodes, --cluster check, --cluster add-node, --cluster reshard. For full documentation, refer to the official Redis documentation. For Redis Cluster Docker, use docker run -d --name redis-cluster ... with the same configuration.

What's Included in the Work

When ordering a turnkey Redis Cluster setup, we provide:

  • Deployment of a 6-node cluster (3 masters + 3 replicas) on your servers or cloud.
  • Configuration of cluster clients (phpredis, Predis, Laravel).
  • Code adaptation: implementing hash tags, handling MOVED/ASK errors, retry logic.
  • Monitoring via Prometheus and Grafana.
  • Architecture documentation and operational instructions.
  • Team training on cluster basics.
Stage Duration Cost (approx)
Cluster deployment (6 nodes) 1–2 days $1,500
Client configuration and code adaptation 1–2 days $2,000
Monitoring and documentation 1 day $800
Team training 0.5 day $500
Total 3–5 days $4,800

Contact us for a project assessment. Get a consultation on code adaptation and monitoring setup.

Our Experience

We have worked with Redis in production for over 5 years. We have deployed clusters for 15+ projects with loads up to 100k requests per second. We hold Redis Developer certification. We have case studies of migration from Redis Sentinel to Cluster for e-commerce, FinTech, and AdTech. Our typical cost savings with cluster migration are around 30% compared to upgrading to a larger single instance.

We guarantee that after setup, the cluster will run without failures provided SLA conditions are met. Reach out — we'll help scale your cache.

Backend Development Services: Laravel, Node.js, Go, Django, PostgreSQL

On a production server at 3:14 AM, the Laravel Jobs queue stopped processing. 40,000 unprocessed jobs in Redis. Cause: worker crashed due to a memory leak in one of the Jobs (leak via a static variable in an Eloquent observer), supervisor didn't restart it because of misconfigured stopwaitsecs. This is not a hypothetical scenario — it's Tuesday. We analyzed such an incident on a project with 500 RPS load: diagnosis took 4 hours, fix — 20 minutes. So you don't lose money on downtime, we offer backend development services with a focus on production-grade reliability. We'll assess your project in 2 days.

Backend is what works when no one is watching. Or doesn't work. We guarantee you'll have the first option.

How do we ensure production-grade reliability from day one?

What we do correctly from day one

Service Layer over Fat Controllers. Controller receives HTTP request, validates it via Form Request, passes data to Service, returns response. Business logic in Service, not Controller. This sounds trivial, but most legacy projects have controllers with 500 lines and SQL queries inside.

Repository Pattern we use cautiously. If you just wrap Model::where(...) in a repository method — that's boilerplate without benefit. Repository is justified when: you need to abstract from the data source (DB + cache + external API) or when query logic is complex enough to isolate.

Jobs, Events, Listeners. Everything that can be async — make async. Sending email, PDF generation, external API sync, aggregate recalculation — into Queue. Laravel Horizon for queue monitoring in Redis: see throughput, failed jobs, processing time per queue.

How Octane handles high load

Laravel Octane with RoadRunner or Swoole keeps the app in memory between requests — removes bootstrap overhead (config loading, class autoloading) on each HTTP request. Gain: 3–8x on synthetic benchmarks, 2–4x on real applications. Important: no state between requests in static variables — that leads to exactly the incidents from the beginning. We use this in projects with >1000 RPS.

What to do about N+1 queries

N+1 is the most common cause of slow pages in Laravel apps. Standard story: page worked fine on dev with 10 records, on production with 10,000 — 8-second load.

Laravel Debugbar in dev environment shows the number of queries per page. More than 20 queries per page — signal for audit.

Model::preventLazyLoading(! app()->isProduction());

Telescope for profiling in staging: logs all queries, jobs, mail, notifications with time detail. Numbers: after implementing eager loading, page load time drops from 8s to 0.3s — 27 times faster.

PostgreSQL: indexes that are actually needed

PostgreSQL 14+ is the primary DB on all projects. We use PgBouncer + PostgreSQL combination. 10+ years experience, more than 50 backend projects, 5 years on the market.

How PostgreSQL helps avoid slow queries

Composite indexes for frequent WHERE + ORDER BY. If you have WHERE user_id = ? AND status = ? ORDER BY created_at DESC — you need (user_id, status, created_at DESC). A separate index on (user_id) doesn't help much with sorting.

Partial indexes. If 95% of queries go with WHERE status = 'active':

CREATE INDEX idx_orders_active ON orders (created_at DESC)
WHERE status = 'active';

The index is small, fast, covers the main load.

GIN indexes for JSONB and arrays. @> operator without GIN index — seq scan. With index — fast even on millions of rows.

GIN for full-text search. to_tsvector + GIN instead of LIKE '%query%'. LIKE without index is always seq scan. With pg_trgm extension and gin_trgm_ops — supports LIKE with index, useful for CRM search by partial match.

Connection pooling: why it's more important than it seems

Rails, Laravel, Django open a new connection to PostgreSQL for each PHP/Python process. With 100 workers — 100 connections. PostgreSQL starts degrading from 200–300 active connections — overhead on connection management becomes significant.

PgBouncer — connection pooler in front of PostgreSQL. Transaction pooling mode: connection to PostgreSQL is occupied only during a transaction, returned to pool between requests. 1000 application workers → 20–50 actual connections to PostgreSQL. This reduces latency by 40% and hosting costs by 30%.

Node.js with Fastify: when it's better than Laravel

Node.js is justified for:

  • Realtime: WebSocket servers, Server-Sent Events, chat, live updates
  • Streaming: large files, video, streaming data
  • High I/O concurrency: many parallel requests to external APIs without heavy business logic
  • Serverless: Lambda/Cloud Functions — Node.js starts faster than PHP

Fastify over Express: 2–3 times faster on benchmarks, built-in JSON Schema validation, better TypeScript support, plugin architecture.

Typical realtime architecture: Laravel — core business logic and REST API. Node.js + Socket.io or ws — WebSocket server. Laravel publishes events to Redis Pub/Sub, Node.js subscribes and broadcasts to clients. This separation allows scaling the WebSocket server independently of the main app.

Go: microservices and high load

Go we use for:

  • High-load microservices (>10,000 RPS)
  • Background workers with strict latency requirements
  • DevOps tools and CLI
  • gRPC services in microservice architecture

Goroutines — thousands of times cheaper than OS threads. 10,000 concurrent connections on Go is normal on one server.

But Go is not a silver bullet. Development is slower than Laravel: more boilerplate, no ORM at Eloquent level, error handling with if err != nil everywhere. Justified only when performance is a real requirement, not an assumption.

Django and Python backend

Django with DRF (Django REST Framework) — for tasks where Python is needed: ML pipelines, data processing, integrations with AI tools.

Celery for background tasks — similar to Laravel Queue but more complex to configure. Celery Beat for cron tasks.

Django ORM vs raw SQL: ORM is convenient for CRUD. For analytical queries with multiple JOINs, window functions, and CTEs — connection.execute() with raw SQL is more readable and predictable.

Redis: not just cache

Redis in our projects plays multiple roles:

Role Details
Cache Caching results of heavy queries, HTML fragments
Queues Backend for Laravel Queue / Celery
Session store Distributed sessions in multi-instance environment
Pub/Sub Realtime events between services
Rate limiting Sliding window counters for API throttling
Leaderboards Sorted Sets for rankings

Redis Cluster for horizontal scaling. Sentinel for automatic failover on standalone setups.

Deployment and infrastructure

Docker + docker-compose — standard for local development and production. Each service in a container: PHP-FPM/Octane, Nginx, PostgreSQL, Redis, Queue Worker, Scheduler.

CI/CD via GitHub Actions:

  1. Run tests (PHPUnit / Pest, Vitest, Playwright)
  2. Build Docker image
  3. Push to Container Registry
  4. Deploy: docker pull → docker-compose up -d on server, or Kubernetes rolling update

Zero-downtime deploy for Laravel: php artisan down --secret=TOKEN is not needed with proper configuration. Strategy: new container starts next to the old one, Nginx switches traffic after health check, old container stops.

Monitoring: Sentry for exception tracking with alerting in Slack/Telegram. Grafana + Prometheus (or Grafana Cloud) for metrics: CPU, memory, request rate, queue depth, database connection count. Alerts on: error rate > 1%, p99 latency > 2s, queue depth > 1000 jobs.

What's included in turnkey work

  • Architecture design (API documentation, DB schema, service diagram)
  • Implementation according to agreed specification with code review
  • CI/CD, monitoring, alerting setup
  • Load testing (k6, wrk) with report
  • Handover of source code, access, deployment instructions
  • Training of customer's team (2-3 sessions)
  • Warranty support for 1 month after delivery

Timeline benchmarks

Task Timeline
REST API for mobile/SPA (medium complexity) 6–12 weeks
Backend with complex business logic + integrations 12–20 weeks
High-load service on Go 8–16 weeks
Migration from legacy PHP to Laravel 16–32 weeks

Pricing is calculated individually after analyzing load, integrations, and business logic. Contact us for a free audit of your current backend — get an optimization plan in 2 days. Request a consultation.