Message buffer system with Redis for efficient processing
🚀 Message-Batching Buffer Workflow (n8n)
This workflow implements a lightweight message-batching buffer using Redis for temporary storage and a JavaScript consolidation function to merge messages. It collects incoming user messages per session, waits for a configurable inactivity window or batch size threshold, consolidates buffered messages via custom code, then clears the buffer and returns the combined response—all without external LLM calls.
🔑 Key Features
- Redis-backed buffer queues incoming messages per
context_id. - Centralized Config Parameters node to adjust thresholds and timeouts in one place.
- Dynamic wait time based on message length (configurable
minWords,waitLong,waitShort). - Batch trigger fires on inactivity timeout or when
buffer_count≥batchThreshold. - Zero-cost consolidation via built-in JavaScript Function (
consolidate buffer)—no GPT-4 or external API required.
⚙️ Setup Instructions
-
Extract Session & Message
- Trigger:
When chat message received(webhook) orWhen clicking ‘Test workflow’(manual). - Map inputs: set variables
context_idandmessageinto a Set node named Mock input data (for testing) or a proper mapping node in production.
- Trigger:
-
Config Parameters
-
Add a Set node Config Parameters with:
minWords: 3 # Word threshold waitLong: 10 # Timeout (s) for long messages waitShort: 20 # Timeout (s) for short messages batchThreshold: 3 # Messages to trigger batch early -
All downstream nodes reference these JSON values dynamically.
-
-
Determine Wait Time
-
Node: get wait seconds (Code)
-
JS code:
const msg = $json.message || ''; const wordCount = msg.split(/\s+/).filter(w => w).length; const { minWords, waitLong, waitShort } = items[0].json; const waitSeconds = wordCount < minWords ? waitShort : waitLong; return [{ json: { context_id: $json.context_id, message: msg, waitSeconds } }];
-
-
Buffer Message in Redis
- Buffer messages:
LPUSH buffer_in:{{$json.context_id}}with payload{text, timestamp}. - Set buffer_count increment:
INCR buffer_count:{{$json.context_id}}with TTL{{$json.waitSeconds + 60}}. - Set last_seen: record
last_seen:{{$json.context_id}}timestamp with same TTL.
- Buffer messages:
-
Check & Set Waiting Flag
- Get waiting_reply: if null, Set waiting_reply to
truewith TTL{{$json.waitSeconds}}; else exit.
- Get waiting_reply: if null, Set waiting_reply to
-
Wait for Inactivity
- WaitSeconds (webhook): pauses for
{{$json.waitSeconds}}seconds before batch evaluation.
- WaitSeconds (webhook): pauses for
-
Check Batch Trigger
- Get last_seen and Get buffer_count.
- IF
(now - last_seen) ≥ waitSeconds * 1000ORbuffer_count ≥ batchThreshold, proceed; else use Wait node to retry.
-
Consolidate Buffer
-
consolidate buffer (Code):
const j = items[0].json; const raw = Array.isArray(j.buffer) ? j.buffer : []; const buffer = raw.map(x => { try { return typeof x === 'string' ? JSON.parse(x) : x; } catch { return null; } }).filter(Boolean); buffer.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp)); const texts = buffer.map(e => e.text?.trim()).filter(Boolean); const unique = [...new Set(texts)]; const message = unique.join(' '); return [{ json: { context_id: j.context_id, message } }];
-
-
Cleanup & Respond
- Delete Redis keys:
buffer_in,buffer_count,waiting_reply,last_seen(for thecontext_id). - Return consolidated
messageto the user via your chat integration.
- Delete Redis keys:
🛠 Customization Guidance
- Adjust thresholds by editing the Config Parameters node.
- Change concatenation (e.g., line breaks) by modifying the
joinseparator in the consolidation code. - Add filters (e.g., ignore empty or system messages) inside the consolidation Function.
- Monitor performance: for very high volume, consider sharding Redis keys by date or user segments.
© 2025 Innovatex • Automation & AI Solutions • innovatexiot.carrd.co • LinkedIn
n8n Workflow: Message Buffer System with Redis for Efficient Processing
This n8n workflow demonstrates a foundational message buffering system using Redis, designed for scenarios where messages need to be temporarily stored and processed efficiently, potentially with a delay or conditional routing. It showcases how to receive messages, store them in Redis, and then conditionally process them or introduce a delay.
What it does
This workflow outlines the following key steps:
- Triggers: The workflow can be initiated in three ways:
- Manual Trigger: For immediate testing and execution by clicking "Execute workflow".
- Chat Trigger: Designed to activate when a chat message is received, suggesting integration with conversational platforms.
- Execute Workflow Trigger: Allows this workflow to be called as a sub-workflow from another n8n workflow.
- Edit Fields (Set): This node is typically used to prepare or transform incoming data, ensuring it's in the correct format before further processing.
- If Node: Implements conditional logic. Messages can be routed down different paths based on specific criteria defined in this node.
- Redis Integration: One branch of the
Ifnode leads to a Redis node, indicating that messages satisfying certain conditions are stored in a Redis database. - Wait Node: Another branch of the
Ifnode leads to aWaitnode, which introduces a configurable delay before further processing. - No Operation (NoOp): This node serves as a placeholder or a terminal point for branches that don't require further action, useful for debugging or marking the end of a specific logic path.
- Code Node: Allows for custom JavaScript execution, providing flexibility for complex data manipulation, external API calls, or custom logic that isn't covered by standard n8n nodes.
- Sticky Note: Provides documentation within the workflow itself, offering context or instructions for specific parts of the flow.
Prerequisites/Requirements
To use this workflow, you will need:
- n8n Instance: A running n8n instance (self-hosted or cloud).
- Redis Account/Instance: Access to a Redis database for storing buffered messages. You will need to configure Redis credentials in n8n.
- Chat Platform (Optional): If using the "Chat Trigger", integration with a compatible chat platform (e.g., Slack, Telegram, Discord) will be required, along with the necessary n8n credentials for that platform.
Setup/Usage
- Import the Workflow: Download the provided JSON and import it into your n8n instance.
- Configure Credentials:
- Set up your Redis credentials in n8n if you haven't already.
- If using the "Chat Trigger", configure the necessary credentials for your chat platform.
- Customize Nodes:
- Edit Fields (Set): Adjust the fields to match the incoming data structure and the desired output for Redis.
- If Node: Define the conditions for routing messages. For example, you might check for specific keywords, message types, or sender IDs.
- Redis Node: Configure the Redis operation (e.g.,
SET,LPUSH) and the key/value pairs based on your buffering strategy. - Wait Node: Adjust the delay duration as needed.
- Code Node: Implement any custom logic required for message processing or transformation.
- Activate the Workflow: Once configured, activate the workflow to start processing messages.
- Test: Use the "Manual Trigger" or send a test message via your configured chat platform to ensure the workflow functions as expected.
Related Templates
AI-powered code review with linting, red-marked corrections in Google Sheets & Slack
Advanced Code Review Automation (AI + Lint + Slack) Who’s it for For software engineers, QA teams, and tech leads who want to automate intelligent code reviews with both AI-driven suggestions and rule-based linting — all managed in Google Sheets with instant Slack summaries. How it works This workflow performs a two-layer review system: Lint Check: Runs a lightweight static analysis to find common issues (e.g., use of var, console.log, unbalanced braces). AI Review: Sends valid code to Gemini AI, which provides human-like review feedback with severity classification (Critical, Major, Minor) and visual highlights (red/orange tags). Formatter: Combines lint and AI results, calculating an overall score (0–10). Aggregator: Summarizes results for quick comparison. Google Sheets Writer: Appends results to your review log. Slack Notification: Posts a concise summary (e.g., number of issues and average score) to your team’s channel. How to set up Connect Google Sheets and Slack credentials in n8n. Replace placeholders (<YOURSPREADSHEETID>, <YOURSHEETGIDORNAME>, <YOURSLACKCHANNEL_ID>). Adjust the AI review prompt or lint rules as needed. Activate the workflow — reviews will start automatically whenever new code is added to the sheet. Requirements Google Sheets and Slack integrations enabled A configured AI node (Gemini, OpenAI, or compatible) Proper permissions to write to your target Google Sheet How to customize Add more linting rules (naming conventions, spacing, forbidden APIs) Extend the AI prompt for project-specific guidelines Customize the Slack message formatting Export analytics to a dashboard (e.g., Notion or Data Studio) Why it’s valuable This workflow brings realistic, team-oriented AI-assisted code review to n8n — combining the speed of automated linting with the nuance of human-style feedback. It saves time, improves code quality, and keeps your team’s review history transparent and centralized.
Daily cash flow reports with Google Sheets, Slack & Email for finance teams
Simplify financial oversight with this automated n8n workflow. Triggered daily, it fetches cash flow and expense data from a Google Sheet, analyzes inflows and outflows, validates records, and generates a comprehensive daily report. The workflow sends multi-channel notifications via email and Slack, ensuring finance professionals stay updated with real-time financial insights. 💸📧 Key Features Daily automation keeps cash flow tracking current. Analyzes inflows and outflows for actionable insights. Multi-channel alerts enhance team visibility. Logs maintain a detailed record in Google Sheets. Workflow Process The Every Day node triggers a daily check at a set time. Get Cash Flow Data retrieves financial data from a Google Sheet. Analyze Inflows & Outflows processes the data to identify trends and totals. Validate Records ensures all entries are complete and accurate. If records are valid, it branches to: Sends Email Daily Report to finance team members. Send Slack Alert to notify the team instantly. Logs to Sheet appends the summary data to a Google Sheet for tracking. Setup Instructions Import the workflow into n8n and configure Google Sheets OAuth2 for data access. Set the daily trigger time (e.g., 9:00 AM IST) in the "Every Day" node. Test the workflow by adding sample cash flow data and verifying reports. Adjust analysis parameters as needed for specific financial metrics. Prerequisites Google Sheets OAuth2 credentials Gmail API Key for email reports Slack Bot Token (with chat:write permissions) Structured financial data in a Google Sheet Google Sheet Structure: Create a sheet with columns: Date Cash Inflow Cash Outflow Category Notes Updated At Modification Options Customize the "Analyze Inflows & Outflows" node to include custom financial ratios. Adjust the "Validate Records" filter to flag anomalies or missing data. Modify email and Slack templates with branded formatting. Integrate with accounting tools (e.g., Xero) for live data feeds. Set different trigger times to align with your financial review schedule. Discover more workflows – Get in touch with us
Generate Weather-Based Date Itineraries with Google Places, OpenRouter AI, and Slack
🧩 What this template does This workflow builds a 120-minute local date course around your starting point by querying Google Places for nearby spots, selecting the top candidates, fetching real-time weather data, letting an AI generate a matching emoji, and drafting a friendly itinerary summary with an LLM in both English and Japanese. It then posts the full bilingual plan with a walking route link and weather emoji to Slack. 👥 Who it’s for Makers and teams who want a plug-and-play bilingual local itinerary generator with weather awareness — no custom code required. ⚙️ How it works Trigger – Manual (or schedule/webhook). Discovery – Google Places nearby search within a configurable radius. Selection – Rank by rating and pick the top 3. Weather – Fetch current weather (via OpenWeatherMap). Emoji – Use an AI model to match the weather with an emoji 🌤️. Planning – An LLM writes the itinerary in Markdown (JP + EN). Route – Compose a Google Maps walking route URL. Share – Post the bilingual itinerary, route link, and weather emoji to Slack. 🧰 Requirements n8n (Cloud or self-hosted) Google Maps Platform (Places API) OpenWeatherMap API key Slack Bot (chat:write) LLM provider (e.g., OpenRouter or DeepL for translation) 🚀 Setup (quick) Open Set → Fields: Config and fill in coords/radius/time limit. Connect Credentials for Google, OpenWeatherMap, Slack, and your LLM. Test the workflow and confirm the bilingual plan + weather emoji appear in Slack. 🛠 Customize Adjust ranking filters (type, min rating). Modify translation settings (target language or tone). Change output layout (side-by-side vs separated). Tune emoji logic or travel mode. Add error handling, retries, or logging for production use.