Wake your Cloud Run or Lambda function when the budget is back

The cron post let cron fire often, on every host, and let a bucket decide which firing is the run. The firings that are told no cost one small request each, on hosts you already pay for.

On Cloud Run or Lambda there is no host. The cron line is a Cloud Scheduler job or an EventBridge schedule that invokes a function, and the function’s work is usually limited by something other than time: a partner API that allows 500 calls an hour, a model budget per day, a quota you share with other jobs. So the function wakes every five minutes, starts cold, reads its backlog, asks for budget, learns that the hour’s calls are spent, and exits. Every one of those is a billed invocation that did nothing.

An illustrative count: a schedule every five minutes is 288 invocations a day. If the budget refills once an hour and the backlog uses it up each time, at most 24 of them find budget. The other 264 are the schedule asking a question the budget could have answered by calling.

This post turns the question around. The function asks once, and if the answer is “not yet”, it leaves a waiting request on its bucket, with its own URL, and exits. When the bucket can pay what it asked for, buckette posts to that URL and the function wakes up with work it can do.

1. The budget is a bucket

The partner API allows 500 calls an hour, so the bucket holds 500 calls and is refilled to 500 every hour. Nothing carries over, as with the partner’s own counter.

POST /buckets
{"cbrResources": {"calls": {"raCurrent": 500, "raMaximum": 500, "raReserved": 0,
                            "raUnit": "call", "raMode": "Locking"}},
 "cbrMetadata": {"buckette/bucket-title": "enrichment: partner API, 500 calls an hour"}}

PUT /buckets/<bucket>/replenish-config
{"rcSchedule": {"tag": "Every", "count": 1, "unit": "hours",
                "anchor": "2027-01-02T00:00:00Z"},
 "rcAmounts": {"calls": 500},
 "rcCarryover": "CarryoverNone", "rcOverflow": "OverflowDiscard"}

The function gets a key that can only spend from, and read, this bucket (POST /api-keys with "cakreScopes": ["ScopeConsume", "ScopeRead"] and "cakreBucketId" set to it).

2. Take the budget, or leave a request and exit

One call does both. A consume in Async mode behaves like a strict consume when the bucket can pay: it spends the amount and answers ConsumeSuccess. When it cannot, it does not fail: it registers a pending request and answers ConsumePending. That includes a bucket that has run out (Depleted), where a strict consume would be refused.

POST /buckets/<bucket>/consume
{"crAmounts": {"calls": 100},
 "crMode": {"tag": "Async", "contents": {
   "acMaxDelaySecs": 86400,
   "acAutoConsume": false,
   "acCallbackUrl": "https://enrich-abc123.example.run.app/",
   "acCallbackSecret": "<a secret for the signature>"}}}

acAutoConsume: false is the important part. When the bucket can cover the 100 calls again, buckette does not spend them on the function’s behalf: it posts bucket.resources_available to the callback URL and leaves the budget where it is. The function, woken, makes the same call again and gets its ConsumeSuccess. If the function never comes (a deploy gone wrong), nothing was spent for it. With true, buckette would spend the amount as soon as it is there and post bucket.consumed, which is fine for a receiver that is always up, and wasted budget for one that is not.

The function’s loop is therefore short:

  1. Take the next batch of records, as many as one call to the partner each, up to 100.
  2. Consume that many calls in Async mode, as above.
  3. On ConsumeSuccess, do the work, and go back to 1 while time is left.
  4. On ConsumePending, stop: the request is parked, and the function will be called back.
  5. With an empty backlog, stop without parking anything.

A request waits at most a day (acMaxDelaySecs is capped at 86400). If the bucket still cannot pay by then, buckette posts bucket.consume_expired to the same URL, which is one more wake-up: the function looks at its backlog and parks again if it needs to.

3. The function

The same handler serves Cloud Run and Lambda. It answers three kinds of request: the challenge buckette sends once to verify the URL (below), a signed callback, and its slow schedule (section 5).

import hashlib, hmac, json, os, time, urllib.request

URL, KEY = os.environ["BUCKETTE_URL"], os.environ["BUCKETTE_KEY"]
BUCKET, SELF = os.environ["BUCKETTE_BUCKET"], os.environ["SELF_URL"]
SECRET = os.environ["CALLBACK_SECRET"].encode()

def consume_or_park(n):
    body = {"crAmounts": {"calls": n},
            "crMode": {"tag": "Async", "contents": {
                "acMaxDelaySecs": 86400, "acAutoConsume": False,
                "acCallbackUrl": SELF, "acCallbackSecret": SECRET.decode()}}}
    req = urllib.request.Request(f"{URL}/buckets/{BUCKET}/consume",
        data=json.dumps(body).encode(), method="POST",
        headers={"Authorization": f"Bearer {KEY}",
                 "Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=5) as resp:
        return json.load(resp)["tag"]   # ConsumeSuccess | ConsumePending

def drain(deadline):
    while time.monotonic() < deadline:
        batch = take_records(limit=100)        # your queue or table
        if not batch:
            return                             # no work: park nothing
        tag = consume_or_park(len(batch))
        if tag != "ConsumeSuccess":
            put_back(batch)                    # parked: buckette calls back
            return
        enrich(batch)                          # len(batch) partner calls

def handle(headers, raw):
    msg = json.loads(raw or b"{}")
    if msg.get("event") == "verification.challenge":
        return 200, json.dumps({"challenge": msg["challenge"]})
    if msg.get("source") != "schedule":        # everything else is signed
        want = "sha256=" + hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
        if not hmac.compare_digest(want, headers.get("x-buckette-signature", "")):
            return 401, "bad signature"
    drain(time.monotonic() + 8)                # answer inside buckette's 10 s
    return 204, ""

take_records and put_back are your own queue (a table with FOR UPDATE SKIP LOCKED, a Pub/Sub or SQS subscription): two invocations must not take the same record, which is the queue’s job, not the budget’s. A real schedule trigger should carry a secret of its own; the source field here keeps the sketch short.

The two entry points are a few lines each:

# Cloud Run (functions-framework)
import functions_framework
@functions_framework.http
def main(request):
    status, body = handle({k.lower(): v for k, v in request.headers.items()},
                          request.get_data())
    return body, status

# Lambda, behind a function URL
import base64
def lambda_handler(event, context):
    raw = event.get("body") or ""
    raw = base64.b64decode(raw) if event.get("isBase64Encoded") else raw.encode()
    status, body = handle(event.get("headers", {}), raw)
    return {"statusCode": status, "body": body}

The handler answers within eight seconds because buckette waits ten for an answer. A delivery that gets no answer in time, or a 5xx, or a 429, is tried again: 30 seconds later, then doubling, capped at an hour, eight attempts in all. A 2xx, or any other 4xx, ends it. So a function that starts cold and slowly is called again rather than lost, and a function that did the work but answered late can be called twice. Both are harmless here: a second wake-up asks the bucket again and finds what is left.

If a batch takes longer than a few seconds, do not answer first and keep working in the same invocation: once an invocation has answered, neither platform promises it more CPU. Hand the batch to the platform’s own asynchronous path (an asynchronous Lambda invocation, a Cloud Tasks or Pub/Sub push to the Cloud Run service) and answer 202.

4. Letting buckette call the function

buckette posts JSON to an HTTPS URL, and that is all it does. There is no Cloud Run or Lambda connector, and a delivery carries no Google ID token and no AWS signature: its only headers are Content-Type and, with a secret, X-Buckette-Signature: sha256=<hex HMAC-SHA256 of the raw body>. So the function’s URL has to accept unauthenticated requests at the platform (a Cloud Run service that allows unauthenticated invocations, a Lambda function URL with auth type NONE), and the function itself refuses any callback whose signature does not match, as the handler above does.

buckette also checks the URL before it posts anything to it, as it does for every webhook:

  • It must be https, on a public address. The default addresses of both platforms are.
  • Its host must be on the tenant’s callback allowlist, which an admin key sets: PUT /callback-allowlist with {"calrHosts": ["enrich-abc123.example.run.app"]}. An allowlist that was never set accepts no callback at all.
  • A verified destination must cover it. Deploy the function first, then POST /destinations with {"cdrKind": "url", "cdrValue": "<the function's URL>"}. buckette posts a verification.challenge with a random value to the URL, and the handler echoes it back. That works on a hostname whose DNS you do not control, such as the platform’s default one. A url claim covers that exact URL, which is why the function uses one URL for every callback and tells requests apart by their body. A domain claim (a TXT record) needs a domain of your own in front of the function.

The guide for agents has the details, under “Outbound destination validation”.

5. Keep a slow schedule

The schedule does not go away. It slows down, to every few hours, and it becomes the safety net, for the cases where no callback comes:

  • New work while nothing is parked. A function that stopped with an empty backlog parked nothing, so nothing will call it back. Either the producer of the work invokes it, or the slow schedule finds the backlog.
  • A delivery that was given up on. After eight failed attempts over about an hour, buckette stops trying. The request is not parked any more, and the next scheduled run parks it again.
  • A parked request is one call back. Once it has been answered with bucket.resources_available, it is done. If another job sharing the bucket took the budget first, the woken function’s consume parks a new request, so nothing is lost; but a function that crashed before asking again needs the schedule.

A scheduled run that finds no budget would park one more request on each run. They are harmless (each wakes the function once, and the second finds less or nothing), but a schedule can avoid them: before parking, it reads GET /buckets/<bucket>/pending-consumes and skips the call when one of its requests is already waiting.

What changes, and what does not

The function now runs when there is both work and budget. With the hourly refill above and a backlog that outlasts it, that is about once an hour, a minute or so after the refill, plus a few scheduled runs a day. On a quiet day, it is the scheduled runs alone.

Some things to know before relying on it:

  • The wake-up is not instant. Scheduled refills and waiting requests are both handled by buckette’s scheduler, which passes every 30 seconds, so the callback comes up to about a minute after the budget is back.
  • It wakes for the amount asked, not for any refill. A request for 100 calls is answered when 100 are there. A top-up of 20 wakes nobody.
  • It is per bucket and per request. A standing webhook (POST /webhooks) is the other way to hear about budget, and the one the cron post used: bucket.replenished when a balance went up, or bucket.balance_recovered when a dimension with thresholds is back to normal. Its events filter by name only, so a function behind it is called for every bucket of the tenant and looks the bucket up in the body. For one function and one bucket, the parked request is the closer fit.
  • Delivery is at least once, not exactly once. Retries can repeat a callback. The budget makes a repeat cheap, and the queue makes it safe.

None of this needs a new kind of infrastructure. The function was already an HTTPS endpoint; the budget was already a bucket. What changed is who asks whom. The cron post covers the scheduled side, and the guide for agents has every route used here: “Async consumption — wiring the callback” for the parked request and its callback, and “Outbound destination validation” for the URL.

If you run functions this way, or have one that would not fit, write to hello@buckette.co.