Automated execution cleanup system with n8n API and custom retention rules
Make your n8n instance faster, cleaner, and more efficient by deleting old workflow executions — while keeping only the most recent ones you actually need. Whether you're using n8n Cloud or self-hosted, this lightweight workflow helps reduce database/storage usage and improves UI responsiveness, using only official n8n nodes.
🔍 Description
Automatically clean up old executions in your n8n instance using only official nodes — no external database queries required. Whether you're on the Cloud version or running self-hosted, this workflow helps you optimize performance and keep your instance tidy by maintaining only the most recent executions per workflow.
Ideal for users managing dozens or hundreds of workflows, this solution reduces storage usage and improves the responsiveness of the n8n UI, especially in environments where execution logs can accumulate quickly.
✅ What It Does
- Retrieves up to 250 recent executions across all workflows
- Groups executions by workflow
- Keeps only the most recent N executions per workflow (value is configurable)
- Deletes all older executions (regardless of their status: success, error, etc.)
- Works entirely with native n8n nodes — no external database access required
- Optionally: set the number of executions to keep as 0 to delete all past executions from your instance in a single run
🛠️ How to Set Up
🔑 Create a Personal API Key in your n8n instance: Go to Settings → API Keys → Create a new key
🔧 Create a new n8n API Credential (used by both nodes): In your n8n credentials panel:
Name: anything you like (e.g., “Internal API Access”)
API Key: paste the Personal API Key you just created
Base URL: your full n8n instance URL with the /api/v1 path, e.g. https://your-n8n-instance.com/api/v1
✅ Use this credential in both:
The Get Many Executions node (to fetch recent executions)
The Delete Many Executions node (to remove outdated executions)
🧩 In the “Set Executions to Keep” node:
Edit the variable executionsToKeep and set the number of most recent executions to retain per workflow (e.g. 10)
Tip: Set it to 0 to delete all executions
📦 Note: The “Get Many Executions” node will retrieve up to 250 executions per run — this is the maximum allowed by the n8n API.
🧠 No further setup is required — the filtering and grouping logic is handled inside the Code Node automatically.
🧪 Included Nodes Overview
🕒 Schedule Trigger → Set to run daily, weekly, etc.
📥 Get Many Executions → Fetches past executions via n8n API
🛠️ Set Executions to Keep → Set how many recent ones to keep
🧠 Code Node → Filters out executions to delete per workflow
🗑️ Delete Executions → Deletes outdated executions
💡 Why Use This?
Reduce clutter and improve performance in your n8n instance
Maintain execution logs only when they’re useful
Avoid bloating your storage or database with obsolete data
Compatible with both n8n Cloud and self-hosted setups
Uses only official, supported n8n nodes — no SQL, no extra setup
🔒 This workflow modifies and deletes execution data. Always review and test it first on a staging instance or on a limited set of workflows before using it in production.
Automated Execution Cleanup System with n8n API and Custom Retention Rules
This n8n workflow provides a robust system for automatically cleaning up old n8n workflow executions, helping to manage disk space and maintain a tidy n8n instance. It leverages the n8n API to list and delete executions based on a configurable retention period.
Description
Managing workflow executions in n8n is crucial for performance and storage, especially in busy instances. This workflow automates the process of identifying and removing outdated executions, allowing you to define a custom retention policy for your n8n data.
What it does
- Triggers on a Schedule: The workflow starts at a predefined interval (e.g., daily, weekly) using a
Schedule Triggernode. - Sets Retention Period: A
Setnode defines theretentionDaysvariable, specifying how many days old an execution must be to be considered for deletion. - Executes Cleanup Logic: A
Codenode contains the core logic to:- Calculate the cutoff date based on the
retentionDays. - Make API calls to your n8n instance to list all workflow executions.
- Filter these executions to identify those older than the cutoff date.
- For each identified old execution, make an API call to delete it.
- Calculate the cutoff date based on the
- Interacts with n8n API: The
n8nnode is used within theCodenode to perform the API operations (listing and deleting executions). - Provides Documentation: A
Sticky Notenode offers inline documentation or comments for better understanding of the workflow.
Prerequisites/Requirements
- n8n Instance: An active n8n instance where this workflow will run.
- n8n API Key: An API key for your n8n instance with sufficient permissions to list and delete workflow executions. This will be configured as an n8n credential.
- Basic JavaScript Knowledge (Optional): While the
Codenode is provided, understanding basic JavaScript can be helpful for customizing the cleanup logic.
Setup/Usage
- Import the Workflow: Import the provided JSON into your n8n instance.
- Configure n8n API Credential:
- Go to "Credentials" in your n8n instance.
- Add a new credential of type "n8n API".
- Provide your n8n API Key.
- Configure Retention Days:
- Open the
Edit Fields(Set) node. - Adjust the
retentionDaysvalue to your desired retention period (e.g.,30for 30 days).
- Open the
- Configure Schedule:
- Open the
Schedule Triggernode. - Set the desired interval for the cleanup (e.g., "Every Day" at a specific time).
- Open the
- Activate the Workflow: Save and activate the workflow. It will now automatically clean up old executions based on your configured schedule and retention rules.
Related Templates
AI multi-agent executive team for entrepreneurs with Gemini, Perplexity and WhatsApp
This workflow is an AI-powered multi-agent system built for startup founders and small business owners who want to automate decision-making, accountability, research, and communication, all through WhatsApp. The “virtual executive team,” is designed to help small teams to work smarter. This workflow sends you market analysis, market and sales tips, It can also monitor what your competitors are doing using perplexity (Research agent) and help you stay a head, or make better decisions. And when you feeling stuck with your start-up accountability director is creative enough to break the barrier 🎯 Core Features 🧑💼 1. President (Super Agent) Acts as the main controller that coordinates all sub-agents. Routes messages, assigns tasks, and ensures workflow synchronization between the AI Directors. 📊 2. Sales & Marketing Director Uses SerpAPI to search for market opportunities, leads, and trends. Suggests marketing campaigns, keywords, or outreach ideas. Can analyze current engagement metrics to adjust content strategy. 🕵️♀️ 3. Business Research Director Powered by Perplexity AI for competitive and market analysis. Monitors competitor moves, social media engagement, and product changes. Provides concise insights to help the founder adapt and stay ahead. ⏰ 4. Accountability Director Keeps the founder and executive team on track. Sends motivational nudges, task reminders, and progress reports. Promotes consistency and discipline — key traits for early-stage success. 🗓️ 5. Executive Secretary Handles scheduling, email drafting, and reminders. Connects with Google Calendar, Gmail, and Sheets through OAuth. Automates follow-ups, meeting summaries, and notifications directly via WhatsApp. 💬 WhatsApp as the Main Interface Interact naturally with your AI team through WhatsApp Business API. All responses, updates, and summaries are delivered to your chat. Ideal for founders who want to manage operations on the go. ⚙️ How It Works Trigger: The workflow starts from a WhatsApp Trigger node (via Meta Developer Account). Routing: The President agent analyzes the incoming message and determines which Director should handle it. Processing: Marketing or sales queries go to the Sales & Marketing Director. Research questions are handled by the Business Research Director. Accountability tasks are assigned to the Accountability Director. Scheduling or communication requests are managed by the Secretary. Collaboration: Each sub-agent returns results to the President, who summarizes and sends the reply back via WhatsApp. Memory: Context is maintained between sessions, ensuring personalized and coherent communication. 🧩 Integrations Required Gemini API – for general intelligence and task reasoning Supabase- for RAG and postgres persistent memory Perplexity API – for business and competitor analysis SerpAPI – for market research and opportunity scouting Google OAuth – to connect Sheets, Calendar, and Gmail WhatsApp Business API – for message triggers and responses 🚀 Benefits Acts like a team of tireless employees available 24/7. Saves time by automating research, reminders, and communication. Enhances accountability and strategy consistency for founders. Keeps operations centralized in a simple WhatsApp interface. 🧰 Setup Steps Create API credentials for: WhatsApp (via Meta Developer Account) Gemini, Perplexity, and SerpAPI Google OAuth (Sheets, Calendar, Gmail) Create a supabase account at supabase Add the credentials in the corresponding n8n nodes. Customize the system prompts for each Director based on your startup’s needs. Activate and start interacting with your virtual executive team on WhatsApp. Use Case You are a small organisation or start-up that can not afford hiring; marketing department, research department and secretar office, then this workflow is for you 💡 Need Customization? Want to tailor it for your startup or integrate with CRM tools like Notion or HubSpot? You can easily extend the workflow or contact the creator for personalized support. Consider adjusting the system prompt to suite your business
🎓 How to transform unstructured email data into structured format with AI agent
This workflow automates the process of extracting structured, usable information from unstructured email messages across multiple platforms. It connects directly to Gmail, Outlook, and IMAP accounts, retrieves incoming emails, and sends their content to an AI-powered parsing agent built on OpenAI GPT models. The AI agent analyzes each email, identifies relevant details, and returns a clean JSON structure containing key fields: From – sender’s email address To – recipient’s email address Subject – email subject line Summary – short AI-generated summary of the email body The extracted information is then automatically inserted into an n8n Data Table, creating a structured database of email metadata and summaries ready for indexing, reporting, or integration with other tools. --- Key Benefits ✅ Full Automation: Eliminates manual reading and data entry from incoming emails. ✅ Multi-Source Integration: Handles data from different email providers seamlessly. ✅ AI-Driven Accuracy: Uses advanced language models to interpret complex or unformatted content. ✅ Structured Storage: Creates a standardized, query-ready dataset from previously unstructured text. ✅ Time Efficiency: Processes emails in real time, improving productivity and response speed. *✅ Scalability: Easily extendable to handle additional sources or extract more data fields. --- How it works This workflow automates the transformation of unstructured email data into a structured, queryable format. It operates through a series of connected steps: Email Triggering: The workflow is initiated by one of three different email triggers (Gmail, Microsoft Outlook, or a generic IMAP account), which constantly monitor for new incoming emails. AI-Powered Parsing & Structuring: When a new email is detected, its raw, unstructured content is passed to a central "Parsing Agent." This agent uses a specified OpenAI language model to intelligently analyze the email text. Data Extraction & Standardization: Following a predefined system prompt, the AI agent extracts key information from the email, such as the sender, recipient, subject, and a generated summary. It then forces the output into a strict JSON structure using a "Structured Output Parser" node, ensuring data consistency. Data Storage: Finally, the clean, structured data (the from, to, subject, and summarize fields) is inserted as a new row into a specified n8n Data Table, creating a searchable and reportable database of email information. --- Set up steps To implement this workflow, follow these configuration steps: Prepare the Data Table: Create a new Data Table within n8n. Define the columns with the following names and string type: From, To, Subject, and Summary. Configure Email Credentials: Set up the credential connections for the email services you wish to use (Gmail OAuth2, Microsoft Outlook OAuth2, and/or IMAP). Ensure the accounts have the necessary permissions to read emails. Configure AI Model Credentials: Set up the OpenAI API credential with a valid API key. The workflow is configured to use the model, but this can be changed in the respective nodes if needed. Connect the Nodes: The workflow canvas is already correctly wired. Visually confirm that the email triggers are connected to the "Parsing Agent," which is connected to the "Insert row" (Data Table) node. Also, ensure the "OpenAI Chat Model" and "Structured Output Parser" are connected to the "Parsing Agent" as its AI model and output parser, respectively. Activate the Workflow: Save the workflow and toggle the "Active" switch to ON. The triggers will begin polling for new emails according to their schedule (e.g., every minute), and the automation will start processing incoming messages. --- Need help customizing? Contact me for consulting and support or add me on Linkedin.
Send WooCommerce discount coupons to customers via WhatsApp using Rapiwa API
Who is this for? This workflow is ideal for WooCommerce store owners who want to automatically send promotional WhatsApp messages to their customers when new coupons are created. It’s designed for marketers and eCommerce managers looking to boost engagement, streamline coupon sharing, and track campaign performance effortlessly through Google Sheets. Overview This workflow listens for WooCommerce coupon creation events (coupon.created) and uses customer billing data to send promotional WhatsApp messages via the Rapiwa API. The flow formats the coupon data, cleans phone numbers, verifies WhatsApp registration with Rapiwa, sends the promotional message when verified, and logs each attempt to Google Sheets (separate sheets for verified/sent and unverified/not sent). What this Workflow Does Listens for new coupon creation events in WooCommerce via the WooCommerce Trigger node Retrieves all customer data from the WooCommerce store Processes customers in batches to control throughput Cleans and formats customer phone numbers for WhatsApp Verifies if phone numbers are valid WhatsApp accounts using Rapiwa API Sends personalized WhatsApp messages with coupon details to verified numbers Logs all activities to Google Sheets for tracking and analysis Handles both verified and unverified numbers appropriately Key Features Automated coupon distribution: Triggers when new coupons are created in WooCommerce Customer data retrieval: Fetches all customer information from WooCommerce Phone number validation: Verifies WhatsApp numbers before sending messages Personalized messaging: Includes customer name and coupon details in messages Dual logging system: Tracks both successful and failed message attempts Rate limiting: Uses batching and wait nodes to prevent API overload Data formatting: Structures coupon information for consistent messaging Google Sheet Column Structure A Google Sheet formatted like this ➤ sample The workflow uses a Google Sheet with the following columns to track coupon distribution: | name | number | email | address1 | couponCode | couponTitle | couponType | couponAmount | createDate | expireDate | validity | status | | ----------- | ------------- | --------------------------------------------------- | --------- | ---------- | -------------- | ---------- | ------------ | ------------------- | ------------------- | ---------- | -------- | | Abdul Mannan | 8801322827799 | contact@spagreen.net | mirpur-DOHS | 62dhryst | eid offer 2025 | percent | 20.00 | 2025-09-11 06:08:02 | 2025-09-15 00:00:00 | unverified | not sent | | Abdul Mannan | 8801322827799 | contact@spagreen.net | mirpur-DOHS | 62dhryst | eid offer 2025 | percent | 20.00 | 2025-09-11 06:08:02 | 2025-09-15 00:00:00 | verified | sent | Requirements n8n instance with the following nodes: WooCommerce Trigger, Code, SplitInBatches, HTTP Request, IF, Google Sheets, Wait WooCommerce store with API access Rapiwa account with API access for WhatsApp verification and messaging Google account with Sheets access Customer phone numbers in WooCommerce (stored in billing.phone field) Important Notes Phone Number Format: The workflow cleans phone numbers by removing all non-digit characters. Ensure your WooCommerce phone numbers are in a compatible format. API Rate Limits: Rapiwa and WooCommerce APIs have rate limits. Adjust batch sizes and wait times accordingly. Data Privacy: Ensure compliance with data protection regulations when sending marketing messages. Error Handling: The workflow logs unverified numbers but doesn't have extensive error handling. Consider adding error notifications for failed API calls. Message Content: The current message template references the first coupon only (coupons[0]). Adjust if you need to handle multiple coupons. Useful Links Dashboard: https://app.rapiwa.com Official Website: https://rapiwa.com Documentation: https://docs.rapiwa.com Support & Help WhatsApp: Chat on WhatsApp Discord: SpaGreen Community Facebook Group: SpaGreen Support Website: https://spagreen.net Developer Portfolio: Codecanyon SpaGreen