Skip to main content

Disable Anthropic API keys over spend threshold

This tutorial walks you through building a flow that deactivates Anthropic API keys when their attributed spend exceeds a per-key USD threshold stored in CloudFlow Datastore. Along the way you'll learn how to combine Anthropic Cost and Usage actions with Date/time transform, Datastore, Code, and Notification nodes.

Early preview

Anthropic Admin API actions are available under early preview. To request access, submit a support request.

Goal and objectives

  • Goal: To create a workflow that loads per-key spend thresholds from Datastore, measures spend over a shared rolling lookback window, deactivates keys that exceed their threshold, emails a notice, and records an enforcement event.

  • Objectives: In this tutorial, you'll learn how to:

    • Build a UTC day-aligned reporting window with a date/time transform node.

    • Store configurable thresholds in Datastore and load only enabled rows.

    • Call Anthropic Cost and Usage Admin API actions from the same flow.

    • Use a code node to attribute organization USD spend to API keys by token share.

    • Deactivate keys with updateApiKey and notify recipients with referenced fields.

Below is the complete flow you'll build:

The Anthropic API key spend threshold flow

How the spend check works

Anthropic's Cost API returns organization spend in USD, but it cannot group results by api_key_id. The Messages Usage API can group by API key, but it returns token counts rather than dollars.

This flow therefore:

  1. Reads organization cost for the lookback window.

  2. Reads Messages usage grouped by api_key_id for the same window.

  3. Attributes organization USD to each key in proportion to that key's token share.

  4. Compares each enabled Datastore threshold to the attributed amount.

Daily Cost buckets also require UTC midnight bounds. Afternoon timestamps can snap to an empty range and fail the Cost request, so the date/time node truncates to the start of the day.

Before you begin

  1. Create an Anthropic Admin API connection with an Admin API key that can list and update API keys and read cost and usage reports.

  2. In CloudFlow Datastore, create two tables:

    • Anthropic API Key Spend Thresholds with fields:

      • apiKeyId (text, unique)

      • apiKeyName (text)

      • thresholdUsd (numeric)

      • notifyEmail (text)

      • enabled (boolean)

    • Anthropic API Key Spend Enforcement Events with fields:

      • eventKey (text, unique)

      • apiKeyId, apiKeyName, notifyEmail, action (text)

      • spendUsd, thresholdUsd (numeric)

      • lookbackDays (integer)

      • periodStart, periodEnd, enforcedAt (timestamp)

  3. Add at least one threshold row. Leave enabled set to false until you are ready to enforce, and replace apiKeyId with a real Anthropic API key ID from the Claude Console or a listApiKeys action.

Start building

  1. Sign in to the DoiT console, select Automation and operations from the top navigation mega menu, and then select CloudFlow.

  2. Select Create CloudFlow.

Step 1: Add a trigger

In the What should start your flow block, select Manually start. You can switch to a custom schedule later — for example, to run the check daily — but a manual trigger is easier while you build and test.

Step 2: Build the rolling spend window

Anthropic Cost reports with bucket_width=1d expect UTC midnight bounds. Configure a date/time transform on the manual trigger's startTime field:

  1. Add a Date/time transform node and name it Build rolling spend window.

  2. Select 1. Manually start.startTime as the field to transform.

  3. Add these transforms in order:

    1. Truncate to Day, new field periodEnd.

    2. Format periodEnd as ISO 8601, new field periodEndIso.

    3. Truncate 1. Manually start.startTime to Day again, new field dayStart.

    4. Subtract 1 Days from dayStart, new field periodStart. Change the subtract value later to widen the shared lookback.

    5. Format periodStart as ISO 8601, new field periodStartIso.

    Date/time transform for UTC day bounds

With a subtract value of 1, the window is yesterday 00:00 UTC through today 00:00 UTC — one complete daily Cost bucket. Today's incomplete day is not included, which matches Anthropic's daily aggregation behavior.

Tip

Date/time steps that reference the same node can only use the previous step's new field. After you format periodEnd into a string, truncate the trigger startTime again before subtracting.

Step 3: Load enabled thresholds

  1. Add a Datastore node and name it Load API key thresholds.

  2. Select the Anthropic API Key Spend Thresholds table.

  3. Set Action to Get.

  4. Add a filter: enabled == true.

    Datastore get for enabled thresholds

Keeping thresholds in Datastore lets you change limits, recipients, and which keys are enforced without editing the flow.

Step 4: Read organization costs

  1. Add an Anthropic Perform an action node and name it Read Anthropic org costs.

  2. Select the getCostReport action from the Cost service.

  3. On the Connection tab, select your Anthropic Admin API connection.

  4. On the Parameters tab, set:

    • Starting_at: 2. Build rolling spend window.periodStartIso

    • Ending_at: 2. Build rolling spend window.periodEndIso

    • Bucket_width: 1d

    • Limit: 31

    Do not add group_by[]=api_key_id. The Cost API rejects that dimension.

    Anthropic getCostReport parameters

Cost amounts are returned in lowest currency units as decimal strings. For USD, divide by 100 to get dollars.

Step 5: Read usage by API key

  1. Add another Anthropic action node and name it Read Anthropic API key usage.

  2. Select the getMessagesUsageReport action from the Usage service.

  3. Use the same connection and the same periodStartIso / periodEndIso references.

  4. Set Bucket_width to 1d and Limit to 31.

  5. Select Add additional parameters, choose group_by[], and set the value to api_key_id.

    Anthropic getMessagesUsageReport parameters

Step 6: Find keys over threshold

Stock nodes can load thresholds and call Anthropic, but summing daily buckets, converting cents to USD, attributing spend by token share, and emitting one violation record per over-limit key is clearest in a code node.

  1. Add a Code node and name it Find keys over threshold.

  2. Use an advanced schema for an array of objects with fields such as eventKey, apiKeyId, apiKeyName, spendUsd, thresholdUsd, lookbackDays, periodStart, periodEnd, notifyEmail, action, and enforcedAt.

  3. In the code editor, aggregate Cost amounts into organization USD, sum Usage tokens per api_key_id, attribute spend by token share, and return only keys whose attributed spend meets or exceeds thresholdUsd.

    The comparison logic looks like this:

    const keyTokens = tokensByKey.get(apiKeyId) ?? 0;
    const spendUsd =
    totalTokens > 0
    ? Number(((orgSpendUsd * keyTokens) / totalTokens).toFixed(6))
    : 0;
    if (spendUsd < thresholdUsd) continue;

    Code node that finds keys over threshold

Skip placeholder rows and disabled thresholds so a draft Datastore seed cannot deactivate the wrong key.

Step 7: Deactivate over-limit keys

  1. Add an Anthropic action node and name it Deactivate Anthropic API key.

  2. Select updateApiKey from the Api Keys service.

  3. Set api_key_id to 6. Find keys over threshold.message.apiKeyId and status to inactive.

    Anthropic updateApiKey parameters

CloudFlow runs this action once per violation record returned by the code node.

Step 8: Email a notice

  1. Add a Send a message node and name it Email key disabled notice.

  2. Set Notification provider to Email.

  3. Set the recipient to 6. Find keys over threshold.message.notifyEmail.

  4. Build a subject and message from referenced fields such as apiKeyName, apiKeyId, spendUsd, thresholdUsd, and lookbackDays. Use format(..., "#,##0.00") for currency values when your notification templates support it.

  5. Enable Don't send notification if no results so empty runs stay quiet.

    Email notification for deactivated keys

Step 9: Record enforcement events

  1. Add a Datastore node and name it Record enforcement event.

  2. Select the Anthropic API Key Spend Enforcement Events table.

  3. Set Action to Upsert with upsert key eventKey.

  4. Map columns from 6. Find keys over threshold.message — for example eventKey, apiKeyId, spendUsd, thresholdUsd, periodStart, periodEnd, and enforcedAt.

    Datastore upsert for enforcement events

Using apiKeyId:periodStart:periodEnd as eventKey keeps one audit row per key per reporting window.

Publish and run the flow

  1. In Datastore, set a real apiKeyId, choose a thresholdUsd that matches the behavior you want to verify, set notifyEmail, and flip enabled to true only when you are ready for the flow to deactivate keys.

  2. Select Publish, then select Run.

  3. On the Run history page, expand each step to inspect outputs. A successful dry run with no enabled over-limit keys completes every step and upserts zero enforcement rows.

Completed run history for the spend threshold flow

When a key is over threshold, the flow deactivates it, emails the configured recipient, and writes an enforcement event you can review later in Datastore or on a dashboard widget.

See also