Exactly Once Agent Actions

    by Khristian Kopachelli

    1

    Design retry-safe agent actions using idempotency keys, outcome ledgers, and state reconciliation to prevent double-execution.

    $12

    Secure checkout via Stripe

    Money-back guarantee

    Converts to your local currency at checkout

    Security scanned

    Works with the AI Agents you already use

    Exactly Once Agent Actions

    Example session with this skill installed

    I need to implement a retry-safe Stripe payment action for my agent. If the API times out, I can't risk charging the customer twice. Show me the ledger pattern for this.

    • Read your context and instructions
    • Compiled the exactly once agent

    I have implemented the exactly-once ledger pattern for your Stripe integration. This setup ensures that even if the agent crashes or the network times out, the payment is only processed once by using a durable intent ID and a reconciliation lookup.

    Stripe Effect Ledger Implementation

    import { createLedger, SqliteStore } from 'effect-ledger';
    import Stripe from 'stripe';
    
    const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
    const ledger = createLedger({ 
      store: new SqliteStore({ path: 'effects.db' }) 
    });
    
    const stripeAdapter = {
      async run(ctx, { amount, customerId }) {
        // Pass the ledger's idempotency key directly to Stripe
        return await stripe.paymentIntents.create({
          amount,
          currency: 'usd',
          customer: customerId,
        }, {
          idempotencyKey: ctx.idempotencyKey
        });
      },
    
      async lookup(ctx, { customerId }) {
        // Search for existing intent with this key to reconcile 'unknown' states
        const intents = await stripe.paymentIntents.list({
          customer: customerId,
          limit: 100
        });
        const match = intents.data.find(i => i.metadata.opId === ctx.operationId);
        
        if (match) return { status: 'succeeded', result: match };
        return { status: 'unknown' };
      }
    };
    
    // Usage within agent tool
    const outcome = await ledger.execute({
      scope: `user_${userId}`,
      operationId: `checkout_${cartId}`, // Stable across retries
      input: { amount: 2000, customerId: 'cus_123' },
      adapter: stripeAdapter
    });
    

    Next steps

    1. Initialize your SQLite database using the provided schema for the SqliteStore.
    2. Ensure your operationId is generated at the start of the checkout flow and persisted in your primary database.
    3. Set a leaseMs of at least 30000 to account for slow payment gateway responses.

    Connects securely to your tools. The creator never sees your data.

    About this skill

    Distributed systems are inherently unreliable. When an agent times out on a payment or an API write, you cannot know if the operation failed or if only the response was lost. Retrying blindly leads to double charges and corrupted state.

    This skill provides the architectural patterns and implementation guidance to achieve exactly-once semantics for agentic side effects. It focuses on the effect-ledger pattern to ensure every external action is idempotent, verifiable, and recoverable.

    What it does

    • Durable Intent Tracking saves operation state before execution to prevent orphan actions.
    • Idempotency Enforcement ensures concurrent or repeated calls with the same ID never execute the side effect twice.
    • State Reconciliation handles the "unknown" state when providers time out, using lookup adapters to verify remote status.
    • Lease Fencing prevents stale or slow workers from overwriting newer operation attempts.
    • Fingerprint Validation detects if the same operation ID is being reused for different inputs, preventing data collisions.

    How it works

    1. Initialize the Ledger using a durable store like SQLite or Cloudflare D1 to persist intent and outcomes.
    2. Define an Adapter that implements the run and lookup methods for your specific external provider.
    3. Execute the Action by passing a stable operationId that persists across agent retries.
    4. Handle Uncertainty by checking for unknown status and triggering a reconciliation flow instead of an automatic retry.

    Frameworks & tools

    The implementation references the effect-ledger library for Node.js (v22.13+). It supports SqliteStore via node:sqlite, D1Store for Cloudflare, and MemoryStore for testing.

    Why this beats prompting it yourself

    LLMs often suggest simple try-catch retry loops that ignore the "Two Generals' Problem." This skill enforces a strict state machine that separates intent from outcome, ensuring your agent doesn't double-spend or double-post when the network flinches.

    Use cases

    • Payment Processing where a timeout could result in double-charging a customer.
    • Email/SMS Dispatch to ensure notification bursts don't spam users during API instability.
    • Database Writes across distributed services where standard transactions aren't available.
    • Resource Provisioning in cloud environments where duplicate requests incur costs.

    Known limitations

    Requires Node.js 22.13 or higher for native SQLite support. The leaseMs must be manually tuned to exceed the worst-case provider response time to prevent race conditions.

    How to use

    1. 1

      Connect your agent to the Agensi MCP

      Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup

    2. 2

      Sign in to Agensi

      Your agent shows a sign-in link. Sign in and click Allow.

    3. 3

      Ask for what you need

      Your agent loads this skill and uses it on your task. It always asks before buying a skill.

    Reviews

    No reviews yet

    Be one of the first to try it. Every listed skill goes through the trust checks below.

    Security scanned

    Checked by our 8-point scan before listing

    Fresh listing

    Recently published to Agensi

    Money-back guarantee

    Doesn't do what its page promises? You get your money back.

    Trust & safety

    Security scan

    Security scan passed 5 days ago

    Permissions

    No special permissions declared or detected

    Listed5 days ago

    What's inside

    Frequently Asked Questions

    This skill provides the architectural framework and code patterns to prevent 'double-execution' errors, such as double-charging a customer or sending duplicate emails, which occur when an agent retries an action after a network timeout.

    You will receive a complete implementation guide, the effect-ledger architectural pattern documentation, and pre-built adapters for SQLite and Cloudflare D1 to manage your operation state.

    Unlike a simple retry loop, this skill uses a durable ledger and 'lookup' adapters to verify the actual status of a remote service before deciding whether to re-run an action or recover the existing result.

    Yes, you will need a durable storage layer like SQLite or Cloudflare D1 to persist the intent and outcome ledgers; a MemoryStore is included for local development and testing.

    The skill handles high-concurrency via lease fencing, which prevents multiple agent instances or slow workers from processing the same operation ID simultaneously.

    New in APIs & Backend

    Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for APIs & Backend.