Skip to main content

Process Call Batches

Background worker function invoked on a schedule (cron) that picks up pending, scheduled, and processing batches and initiates outbound calls via Ultravox for each queued contact. Runs every minute via pg_cron.

Endpoint

PropertyValue
Function Namecalls-batch-process
HTTP MethodAny (no method restriction)
AuthenticationNone (cron/internal invocation). Auth check removed for cron compatibility.
Required RoleNone (cron)

Request

Headers

No headers are required. This function is designed to be invoked by a Supabase cron scheduler or internal trigger without user authentication.

Body

No request body is expected. The function discovers work by querying the call_batches table.

Response

Success (200)

{
"batches_processed": 5,
"calls_initiated": 150,
"calls_failed": 2
}

Success -- No Pending Batches (200)

{
"processed": 0,
"message": "No batches to process"
}

Error Responses

StatusCondition
500Failed to fetch batches or unhandled top-level exception

Behavior

  1. Fetch active batches: Queries up to 10 batches with status pending, scheduled, or processing where scheduled_for is null or in the past. Ordered by created_at ascending.
  2. Transition batch status: Moves pending/scheduled batches to processing and sets started_at. Transitions all pending contacts in the batch to queued.
  3. Calculate available slots: For each batch, computes min(calls_per_minute, max_concurrent - in_progress). Skips batches with no available slots.
  4. Fetch queued contacts: Calls get_batch_contacts_to_call RPC to get the next batch of contacts respecting the available slot count.
  5. Process each contact:
    • Marks the contact as in_progress and increments attempts.
    • Calls Ultravox POST /api/calls with medium: { telnyx: { destinationPhoneNumber } } and firstSpeaker: FIRST_SPEAKER_AGENT.
    • Passes batch_id and contact_id in the Ultravox metadata for webhook correlation.
    • On success: inserts a calls record and links it to the contact via call_id.
    • On 429 (rate limited): reverts the contact to queued and stops processing the current batch. The batch will be retried on the next cron run.
    • On other errors: marks the contact as failed with error details and updates batch progress via update_batch_progress RPC.
  6. Rate limiting: Applies a delay of 60000 / calls_per_minute ms between calls within each batch.
  7. Batch completion: When no more contacts remain and no calls are in-progress, marks the batch as completed.
  8. Caching: Caches agency credentials and agent mappings per agency_id / agent_mapping_id to minimize database queries across contacts.

Constants

ConstantValueDescription
MAX_BATCHES_PER_RUN10Maximum number of batches processed per cron invocation

Database Tables / RPCs

Table / RPCOperationDescription
call_batchesRead/WriteFetches active batches, transitions statuses, records errors
campaign_contactsRead/WriteTransitions contact statuses, records call references and failures
callsInsertStores a call record for each successfully initiated call
agent_mappingsReadResolves ultravox_agent_id and ultravox_agent_name for each batch
get_agency_credentials (RPC)ReadRetrieves decrypted Ultravox API key for the batch's agency
get_batch_contacts_to_call (RPC)ReadReturns the next batch of queued contacts respecting slot limits
update_batch_progress (RPC)WriteAtomically increments/decrements batch counters (failed, in_progress)

External APIs

APIMethodEndpointDescription
UltravoxPOST/api/callsInitiates an outbound call via Telnyx for each contact