惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

宝玉的分享
宝玉的分享
Apple Machine Learning Research
Apple Machine Learning Research
J
Java Code Geeks
V2EX - 技术
V2EX - 技术
Hacker News: Ask HN
Hacker News: Ask HN
T
Tailwind CSS Blog
V
Visual Studio Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
月光博客
月光博客
H
Hacker News: Front Page
D
DataBreaches.Net
GbyAI
GbyAI
Recorded Future
Recorded Future
IT之家
IT之家
H
Heimdal Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Schneier on Security
Schneier on Security
P
Privacy International News Feed
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
S
Security Affairs
博客园 - 三生石上(FineUI控件)
M
MIT News - Artificial intelligence
Google Online Security Blog
Google Online Security Blog
L
LINUX DO - 最新话题
Google DeepMind News
Google DeepMind News
The Cloudflare Blog
L
LangChain Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
腾讯CDC
The Last Watchdog
The Last Watchdog
I
Intezer
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Hacker News - Newest:
Hacker News - Newest: "LLM"
Stack Overflow Blog
Stack Overflow Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
U
Unit 42
H
Help Net Security
Simon Willison's Weblog
Simon Willison's Weblog
Y
Y Combinator Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Schneier on Security
T
Tenable Blog
TaoSecurity Blog
TaoSecurity Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
小众软件
小众软件
B
Blog
S
Security @ Cisco Blogs
A
About on SuperTechFans
V
V2EX
T
The Exploit Database - CXSecurity.com

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building a Producer-Consumer Queue with Redis and Haskell Using Hedis
Arnab Das · 2026-05-09 · via DEV Community

TL;DR: We'll build a production-grade producer-consumer queue in Haskell using Redis as the message broker via the Hedis client library. By the end, you'll have a working system that can handle high-throughput job dispatch and consumption — the same pattern I used to process 1M+ payment refunds at Juspay.


Why Redis for a Queue?

When people think "message queue," they reach for Kafka or RabbitMQ. But Redis is often the right call when you need:

  • Low latency — sub-millisecond enqueue/dequeue
  • Simplicity — no broker clusters to manage
  • AtomicityLPUSH/BRPOP are atomic operations, safe under concurrency
  • Visibility — you can inspect the queue state instantly with LLEN

At Juspay, we routed payment refunds through a Redis-backed producer-consumer system. The queue absorbed burst traffic from merchant-triggered refund events and fed a pool of consumers that processed each refund, updated sub-statuses, and called downstream banking APIs — all without a single dropped message.

Let's build that.


What We're Building

┌──────────────┐        LPUSH         ┌─────────────────┐       BRPOP        ┌──────────────┐
│   Producer   │ ──────────────────▶  │   Redis Queue   │ ─────────────────▶ │   Consumer   │
│  (Job sender)│                      │  (List: jobs)   │                    │ (Job worker) │
└──────────────┘                      └─────────────────┘                    └──────────────┘

Enter fullscreen mode Exit fullscreen mode

  • Producer pushes JSON-encoded jobs onto a Redis list using LPUSH
  • Consumer blocks on BRPOP — waking up the instant a job arrives
  • Multiple consumers can run in parallel, each pulling distinct jobs atomically

Prerequisites

  • GHC + Cabal (or Stack) installed
  • A running Redis instance (redis-server or Docker: docker run -p 6379:6379 redis)
  • Basic familiarity with Haskell (do notation, IO)

Project Setup

Create a new Cabal project:

mkdir redis-queue && cd redis-queue
cabal init --non-interactive

Enter fullscreen mode Exit fullscreen mode

Add dependencies to your redis-queue.cabal file:

build-depends:
    base        >= 4.14,
    hedis       >= 0.15,
    aeson       >= 2.0,
    text        >= 1.2,
    bytestring  >= 0.11,
    async       >= 2.2

Enter fullscreen mode Exit fullscreen mode

Install and confirm Hedis is available:

cabal build

Enter fullscreen mode Exit fullscreen mode


Understanding Hedis Basics

Hedis wraps all Redis commands in the Redis monad, which you run against a Connection. Here's the mental model:

-- Open a connection pool
conn <- connect defaultConnectInfo

-- Run Redis commands inside runRedis
runRedis conn $ do
    set "hello" "world"
    get "hello"   -- returns Right (Just "world")

Enter fullscreen mode Exit fullscreen mode

Every command returns Either Reply a — the Left branch is a Redis protocol error, Right is success. In practice you'll pattern-match or use either to handle errors.


Step 1 — Define the Job Type

Create src/Job.hs:

{-# LANGUAGE DeriveGeneric #-}

module Job where

import Data.Aeson   (FromJSON, ToJSON, encode, decode)
import Data.Text    (Text)
import GHC.Generics (Generic)
import Data.ByteString.Lazy (ByteString)

-- Our job payload — swap this for whatever your domain needs
data Job = Job
  { jobId     :: Text
  , jobType   :: Text
  , payload   :: Text
  } deriving (Show, Eq, Generic)

instance ToJSON   Job
instance FromJSON Job

-- The Redis key we'll use as our queue
queueKey :: ByteString
queueKey = "jobs:queue"

Enter fullscreen mode Exit fullscreen mode

Keeping the job type generic means you can serialise anything that has a ToJSON instance — refund requests, email notifications, image processing tasks, whatever fits your system.


Step 2 — The Producer

Create src/Producer.hs:

module Producer where

import Database.Redis
import Data.Aeson          (encode)
import Data.ByteString.Lazy (toStrict)
import Control.Monad        (forM_)
import Job

-- Push a single job onto the left end of the list
enqueue :: Connection -> Job -> IO ()
enqueue conn job = do
    let encoded = toStrict (encode job)
    result <- runRedis conn $ lpush queueKey [encoded]
    case result of
        Left err    -> putStrLn $ "Enqueue error: " ++ show err
        Right count -> putStrLn $ "Job enqueued. Queue depth: " ++ show count

-- Simulate a burst of jobs — e.g. end-of-day refund batch
producerMain :: Connection -> IO ()
producerMain conn = do
    let jobs =
          [ Job "txn-001" "refund" "{\"amount\": 500,  \"currency\": \"INR\"}"
          , Job "txn-002" "refund" "{\"amount\": 1200, \"currency\": \"INR\"}"
          , Job "txn-003" "notify" "{\"email\": \"user@example.com\"}"
          , Job "txn-004" "refund" "{\"amount\": 300,  \"currency\": \"USD\"}"
          , Job "txn-005" "notify" "{\"email\": \"other@example.com\"}"
          ]
    putStrLn "Producer starting — pushing jobs..."
    forM_ jobs (enqueue conn)
    putStrLn "Producer done."

Enter fullscreen mode Exit fullscreen mode

Key point: lpush is atomic. Even if 100 producers call it simultaneously, each job lands on the queue exactly once. Redis serialises concurrent writes internally — no locks needed on your side.


Step 3 — The Consumer

Create src/Consumer.hs:

module Consumer where

import Database.Redis
import Data.Aeson          (decode)
import Data.ByteString.Lazy (fromStrict)
import Control.Monad        (forever)
import Job

-- Process a single job — replace this with your real business logic
processJob :: Job -> IO ()
processJob job = putStrLn $
    "[Worker] Processing " ++ show (jobType job) ++
    " | ID: "              ++ show (jobId job)   ++
    " | Payload: "         ++ show (payload job)

-- Block until a job is available, then process it
consumeOne :: Connection -> IO ()
consumeOne conn = do
    result <- runRedis conn $ brpop [queueKey] 30  -- 30s timeout
    case result of
        Left err           -> putStrLn $ "Redis error: " ++ show err
        Right Nothing      -> putStrLn   "Timeout — no jobs in 30s, polling again..."
        Right (Just (_, raw)) ->
            case decode (fromStrict raw) of
                Nothing  -> putStrLn $ "Failed to decode job: " ++ show raw
                Just job -> processJob job

-- Run forever, consuming jobs as they arrive
consumerMain :: Connection -> IO ()
consumerMain conn = do
    putStrLn "Consumer started — waiting for jobs..."
    forever (consumeOne conn)

Enter fullscreen mode Exit fullscreen mode

brpop is the magic here. It blocks the connection until an item is available on any of the listed keys, then atomically pops and returns it. The 30 is a timeout in seconds — after which it returns Right Nothing so you can loop cleanly rather than hanging forever.

This is fundamentally different from polling (RPOP in a loop with threadDelay) — blocking means zero CPU burn while the queue is empty.


Step 4 — Wire It Together

Create app/Main.hs:

module Main where

import Database.Redis
import Control.Concurrent.Async (concurrently_)
import Producer
import Consumer

main :: IO ()
main = do
    -- Connect to local Redis; swap defaultConnectInfo for your host/port/auth
    conn <- connect defaultConnectInfo

    -- Run producer and consumer concurrently
    -- In production you'd run these as separate processes/services
    concurrently_
        (producerMain conn)
        (consumerMain conn)

Enter fullscreen mode Exit fullscreen mode

concurrently_ from the async package runs both actions in parallel on separate OS threads, waiting for both to finish. In a real deployment you'd run the producer and consumer as separate services — this just wires them together for a clean demo.


Running It

# Terminal 1 — start Redis
redis-server

# Terminal 2 — run the app
cabal run redis-queue

Enter fullscreen mode Exit fullscreen mode

Expected output:

Producer starting — pushing jobs...
Job enqueued. Queue depth: 1
Job enqueued. Queue depth: 2
Job enqueued. Queue depth: 3
Job enqueued. Queue depth: 4
Job enqueued. Queue depth: 5
Producer done.
Consumer started — waiting for jobs...
[Worker] Processing "refund" | ID: "txn-001" | Payload: "{"amount": 500, "currency": "INR"}"
[Worker] Processing "refund" | ID: "txn-002" | Payload: "{"amount": 1200, "currency": "INR"}"
[Worker] Processing "notify" | ID: "txn-003" | Payload: "{"email": "user@example.com"}"
[Worker] Processing "refund" | ID: "txn-004" | Payload: "{"amount": 300, "currency": "USD"}"
[Worker] Processing "notify" | ID: "txn-005" | Payload: "{"email": "other@example.com"}"

Enter fullscreen mode Exit fullscreen mode


Step 5 — Scaling to Multiple Consumers

Want parallel workers? Spawn multiple consumers against the same queue:

import Control.Concurrent.Async (replicateConcurrently_)

main :: IO ()
main = do
    conn <- connect defaultConnectInfo
    -- Run 4 parallel consumer workers
    concurrently_
        (producerMain conn)
        (replicateConcurrently_ 4 (consumerMain conn))

Enter fullscreen mode Exit fullscreen mode

Because BRPOP is atomic, each job is delivered to exactly one consumer — no double-processing. Redis handles the fan-out natively.

You can verify this live:

# In a Redis CLI while the app runs:
redis-cli LLEN jobs:queue   # current queue depth
redis-cli MONITOR           # watch every command in real time

Enter fullscreen mode Exit fullscreen mode


Step 6 — Dead Letter Handling (Production Hardening)

In production, jobs can fail. You don't want failed jobs silently disappearing. Add a dead-letter queue:

deadLetterKey :: ByteString
deadLetterKey = "jobs:dead"

-- Consume with failure handling
consumeSafe :: Connection -> IO ()
consumeSafe conn = do
    result <- runRedis conn $ brpop [queueKey] 30
    case result of
        Right (Just (_, raw)) ->
            case decode (fromStrict raw) of
                Nothing  -> do
                    -- Malformed payload — send to dead letter queue
                    _ <- runRedis conn $ lpush deadLetterKey [raw]
                    putStrLn "Malformed job moved to dead letter queue"
                Just job ->
                    -- Wrap in exception handler for business logic failures
                    processJob job `catch` \(e :: SomeException) -> do
                        _ <- runRedis conn $ lpush deadLetterKey [raw]
                        putStrLn $ "Job failed, dead-lettered: " ++ show e
        _ -> pure ()

Enter fullscreen mode Exit fullscreen mode

Now failed jobs accumulate in jobs:dead where you can inspect, replay, or alert on them — no silent data loss.


Connecting to a Real Redis Host

For production (Redis Cloud, AWS ElastiCache, etc.):

import Database.Redis

productionConnInfo :: ConnectInfo
productionConnInfo = defaultConnectInfo
    { connectHost     = "your-redis-host.example.com"
    , connectPort     = PortNumber 6379
    , connectAuth     = Just "your-auth-password"
    , connectDatabase = 0
    , connectMaxConnections = 50   -- connection pool size
    }

main :: IO ()
main = do
    conn <- connect productionConnInfo
    ...

Enter fullscreen mode Exit fullscreen mode

For TLS (Redis Cloud, Upstash, etc.), use checkedConnect with connectTLSParams set.


What We Built vs. What Juspay Ran

The pattern here is the same core design behind Juspay's refund processing pipeline — with a few additions at scale:

This Tutorial Production at Juspay
In-memory job type Protobuf-encoded payloads
Single queue key Separate queues per refund type/priority
brpop timeout loop Supervised consumer pools with health checks
putStrLn processing Downstream bank API calls + DB writes
Basic dead-letter Dead-letter + retry with exponential backoff

The Redis primitives (LPUSH, BRPOP, atomic pops) are identical. Scaling up is mostly operational — more consumer replicas, queue-per-priority, monitoring via LLEN metrics fed into dashboards.


Key Takeaways

  • LPUSH + BRPOP is Redis's native producer-consumer primitive — atomic, fast, and simple
  • Hedis gives you a type-safe, monadic interface to Redis in Haskell with connection pooling built in
  • Blocking pop (BRPOP) beats polling — zero CPU overhead while the queue is idle
  • Dead-letter queues are non-negotiable in production — never let failed jobs disappear silently
  • This pattern scales horizontally: add consumers, add producers, the queue fans out automatically

Full Source Code

The complete working project is on GitHub: https://github.com/arnabdas1999/redis-hedis-queue


What's Next?

  • Priority queues — use multiple Redis lists (jobs:high, jobs:low) and pass both keys to BRPOP; Redis pops from the first non-empty list
  • Delayed jobs — use a Redis Sorted Set with the scheduled timestamp as the score; a scheduler process moves ready jobs to the main queue
  • Exactly-once delivery — combine BRPOPLPUSH with a processing list and a visibility timeout

Drop questions in the comments — happy to dig into any of these.


Arnab Das is an MS student at NYU Tandon and a software engineer who worked on payment infrastructure at Juspay, processing 200M+ daily transactions. Find him on LinkedIn and GitHub.