Flushing Events in Serverless Environments

The send_event and sendEvent methods on the Tracer SDKs are "fire and forget"; they return immediately and events are sent in the background. In long-running application environments like Kubernetes or similar, this allows you to continue processing—such as completing a request or workload—without waiting for the event to be sent.

In short-lived environments like serverless functions, however, you will need to explicitly flush events before program exit to avoid losing them. This is because serverless environments like AWS Lambda will terminate your function as soon as it returns, bypassing the graceful shutdown flow that is typically followed when a long-running application is shut down or restarted.

from autoblocks.tracer import AutoblocksTracer
from autoblocks.tracer import flush

def handler(event, context):
  tracer = AutoblocksTracer()

  # The `send_event` method returns immediately
  tracer.send_event("my-event")

  # In a serverless environment we want to explicitly
  # flush events before the function exits
  flush()

  return "ok"

Cloudflare Workers

Cloudflare Workers expose a waitUntil function that allows users to perform cleanup tasks after the response has been sent. This is a good place to call flush:

import {
  AutoblocksTracer,
  flush,
} from '@autoblocks/client';

export default {
  async fetch(request, env, context) {
    const tracer = new AutoblocksTracer();

    // The `sendEvent` method returns immediately
    tracer.sendEvent('my-event');

    // Flush the events
    // NOTE: Does NOT block / wait
    context.waitUntil(flush());

    // The response can be returned before
    // the events have been flushed
    return 'ok';
  },
};