Redis Message Queues: Pub/Sub and Streams 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 Message Queues: Pub/Sub and Streams Setup
Medium
~2-3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1362
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1253
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    958
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1190
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    931
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    949

Setting Up Redis Message Queues: Using Pub/Sub and Streams

Imagine your e-commerce store sending 10,000 emails per hour. If sent synchronously, the server hangs for a minute, and the user waits for a response. An asynchronous Redis queue solves this: emails are sent in the background, and the request is processed instantly. In 5 years of work, we have implemented Redis queues in 50+ projects, reducing server load by up to 70% and saving clients an average of $2,000/month on infrastructure costs.

Redis Pub/Sub and Streams are two popular solutions for asynchronous task processing. We help set up such infrastructure turnkey starting at $500, guaranteeing zero data loss with Streams. We'll assess your project for free.

How to Choose Between Pub/Sub and Streams?

Redis provides two mechanisms for async messaging: Pub/Sub — simple fire-and-forget without persistence, and Streams — a persistent queue with consumer groups, similar to a lightweight Kafka. The choice depends on the task: real-time notifications (Pub/Sub) or a reliable task queue (Streams).

Feature Pub/Sub Streams Lists (LPUSH/BRPOP)
Persistence No Yes Yes
Consumer groups No Yes No
History replay No Yes No
Complexity Minimal Medium Minimal
Performance at 10K msg/s 2.1 ms latency 3.4 ms latency 1.8 ms latency
Use case Real-time events Task queue Simple queue

Need a reliable queue? Our clients typically save 30% on development time by using Streams instead of custom retry logic. Contact us — we'll help you choose the optimal option.

Why Redis Streams Are Better Than Pub/Sub for Critical Tasks

Streams are 2–3 times more convenient than Pub/Sub when scaling: they support consumer groups, allow acknowledging processing and re-reading failed messages. Pub/Sub is a simple option for real-time events, but as load increases or delivery guarantees are required, choose Streams. This leads to 30% savings on engineer hours: no need to write custom retry logic. Additionally, infrastructure costs decrease by up to 50% due to fewer downtime events.

Setting Up Redis Pub/Sub

Suitable for real-time notifications within the application. Messages are not persisted — if a subscriber is disconnected, the message is lost.

// Laravel: publishing via Redis Pub/Sub
use Illuminate\Support\Facades\Redis;

// Publisher
Redis::publish('user-notifications', json_encode([
    'user_id' => $userId,
    'type'    => 'order.shipped',
    'message' => 'Your order has been shipped',
]));

// Subscriber (console command)
class RedisSubscribeCommand extends Command
{
    protected $signature = 'redis:subscribe';

    public function handle(): void
    {
        Redis::subscribe(['user-notifications'], function (string $message) {
            $data = json_decode($message, true);
            broadcast(new UserNotificationEvent($data));  // → WebSocket
        });
    }
}

Setting Up Redis Streams

Streams are the right choice for a task queue on Redis. Messages are stored in a stream, consumer groups track progress, pending entries track unprocessed messages. Delivery guarantee: a message is deleted only after XACK.

# Create a stream and add a message
XADD emails * user_id 123 email [email protected] template welcome

# Create a consumer group
XGROUP CREATE emails email-workers $ MKSTREAM

# Read new messages (worker 1)
XREADGROUP GROUP email-workers worker-1 COUNT 10 BLOCK 5000 STREAMS emails >

# Acknowledge processing
XACK emails email-workers <message-id>

How to Set Up Consumer Groups in Redis Streams?

Consumer groups allow distributing messages among workers. Each worker receives unique messages, and pending entries track unprocessed ones. This is the foundation of fault tolerance.

PHP Worker Example

use Illuminate\Support\Facades\Redis;

class RedisStreamWorker
{
    private string $stream = 'emails';
    private string $group = 'email-workers';
    private string $consumer;

    public function __construct()
    {
        $this->consumer = gethostname() . ':' . getmypid();
        $this->ensureGroup();
    }

    private function ensureGroup(): void
    {
        try {
            Redis::xgroup('CREATE', $this->stream, $this->group, '$', true);
        } catch (\Throwable) {
            // Group already exists
        }
    }

    public function run(): void
    {
        while (true) {
            // First process pending (unacknowledged from previous run)
            $pending = Redis::xreadgroup(
                $this->group, $this->consumer,
                [$this->stream => '0'],  // '0' = pending messages
                10
            );
            $this->processMessages($pending);

            // Then new messages
            $messages = Redis::xreadgroup(
                $this->group, $this->consumer,
                [$this->stream => '>'],  // '>' = only new
                10,
                5000  // block for 5 seconds
            );
            $this->processMessages($messages);
        }
    }

    private function processMessages(?array $streams): void
    {
        if (!$streams) return;

        foreach ($streams[$this->stream] ?? [] as [$id, $fields]) {
            try {
                $this->handleEmail($fields);
                Redis::xack($this->stream, $this->group, $id);
            } catch (\Throwable $e) {
                Log::error('Stream message failed', ['id' => $id, 'error' => $e->getMessage()]);
                // Message stays pending — will be re-read on next run
            }
        }
    }

    private function handleEmail(array $fields): void
    {
        Mail::to($fields['email'])->send(new TemplateMail($fields['template'], $fields));
    }
}

Node.js Worker Example

import Redis from 'ioredis';

const redis = new Redis({ host: 'redis', port: 6379 });
const STREAM = 'emails';
const GROUP = 'email-workers';
const CONSUMER = `worker-${process.pid}`;

async function startWorker(): Promise<void> {
  // Create group if not exists
  try {
    await redis.xgroup('CREATE', STREAM, GROUP, '$', 'MKSTREAM');
  } catch { /* group exists */ }

  while (true) {
    const messages = await redis.xreadgroup(
      'GROUP', GROUP, CONSUMER,
      'COUNT', '10',
      'BLOCK', '5000',
      'STREAMS', STREAM, '>'
    ) as [string, [string, string[]][]][] | null;

    if (!messages) continue;

    for (const [, entries] of messages) {
      for (const [id, fields] of entries) {
        const data = Object.fromEntries(
          fields.reduce((acc, val, i) => (i % 2 === 0 ? acc.push([val, fields[i+1]]) : acc, acc), [] as [string,string][])
        );

        try {
          await sendEmail(data);
          await redis.xack(STREAM, GROUP, id);
        } catch (err) {
          console.error('Email failed:', id, err);
        }
      }
    }
  }
}

Comparison of PHP and Node.js for Worker Implementation

Feature PHP (Laravel) Node.js (ioredis)
Parallelism Processes (supervisor) Event loop
Pending handling Built-in (Laravel Horizon) Manual
Popularity Widely used High performance
Setup complexity Medium Low

Stream Management and Trimming

# Trim stream to last 10000 messages
XTRIM emails MAXLEN ~ 10000

# Automatically on add
XADD emails MAXLEN ~ 100000 * user_id 123 template welcome

Monitoring and Debugging

Track pending entries — unprocessed messages. If their count rises, the worker is falling behind. Use XINFO STREAM emails to check status. Set up alerts on pending length. For example, when pending exceeds 1000, we send an alert to Slack/Telegram.

Redis Streams — a persistent queue with consumer groups. (Redis Documentation)[https://redis.io/docs/latest/develop/data-types/streams/]

Monitoring details:

  • Alerts in Telegram/Slack when pending exceeds threshold (e.g., > 1000).
  • Log errors with message ID for manual reprocessing.
  • Use XCLAIM to reassign stuck messages to another worker.

Typical Mistakes and Solutions

  • No pending processing: worker crashed, messages stuck. Solution — always process pending on startup.
  • No idempotency guarantee: duplicate email. Use idempotency key.
  • Too aggressive trimming: lose unprocessed messages. Use ~ (tilde) for approximate trimming.

What's Included and Timelines

  1. Requirements analysis and stream schema design.
  2. Implementation of workers in PHP or Node.js with error handling.
  3. Configuration of consumer groups, pending entries, and monitoring.
  4. Operations documentation (trimming, alerts).
  5. Team training (1 hour).
  6. Code warranty — 3 months.

Basic Streams worker implementation (email, notifications) — starts at $500, 1–2 days. With monitoring, alerts, and documentation — $1,200, 2–3 days. Cost is calculated individually based on project complexity.

Contact us for a free consultation — we'll assess your project within 1 day. Save up to $2,000/month on server resources and developer time with our Redis message queue setup.

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.