Agent Batch Processing

Production-grade guide to agent batch processing covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

Agent batch processing is a pattern where a single agent or agent cluster executes a sequence of independent, often data-heavy tasks in a scheduled or triggered batch, rather than processing inputs individually. It matters when data arrives in large volumes—thousands of records, files, or sensor readings—and the agent must apply consistent, complex logic across all items with minimal latency and maximal resource efficiency. This approach is essential for nightly ETL jobs, bulk file transformations, predictive model inference on historical data, and periodic compliance audits.

Core Workflow: Submitting and Monitoring Batches

A batch job begins by submitting a batch request containing a list of tasks, each with its own input data and execution parameters. The agent system returns a batch ID and immediately begins processing. The agent may process items in parallel, with configurable concurrency and resource allocation.

To submit a batch job, clients use a standard HTTP POST request to /api/batches with a JSON body:

{
  "name": "user-profile-enrichment-2024-06-17",
  "description": "Enrich 124K profiles with location and social data",
  "task_type": "enrich-user-profile",
  "concurrency": 16,
  "timeout_seconds": 300,
  "input_data": [
    {
      "id": "user-1042",
      "email": "[email protected]",
      "signup_timestamp": "2023-04-15T08:30:00Z"
    },
    {
      "id": "user-1043",
      "email": "[email protected]",
      "signup_timestamp": "2023-04-15T09:15:00Z"
    }
  ]
}

The response includes a batch_id, status, and created_at:

{
  "batch_id": "batch-9c3f1a7d",
  "status": "submitted",
  "created_at": "2024-06-17T01:23:45Z",
  "total_tasks": 124000,
  "submitted_tasks": 124000
}

Monitoring a batch is done via GET /api/batches/{batch_id}. The agent updates the status as processing progresses:

{
  "batch_id": "batch-9c3f1a7d",
  "status": "processing",
  "progress": {
    "total": 124000,
    "completed": 31542,
    "failed": 178,
    "started_at": "2024-06-17T01:24:10Z"
  },
  "metrics": {
    "avg_task_duration_ms": 423,
    "peak_memory_mb": 1280,
    "total_cpu_seconds": 14320
  },
  "errors": [
    {
      "task_id": "user-1042",
      "error_code": "network_timeout",
      "message": "Failed to fetch location data from geocoding service",
      "details": {
        "url": "https://geo.example.com/v1/coordinates?address=New+York",
        "timeout_ms": 5000,
        "received": null,
        "response_time_ms": 5120
      }
    }
  ]
}

Failure Modes in Batch Execution

The most common silent failure is task loss due to incomplete batch commit. If the agent crashes mid-batch and the batch is not atomic, some tasks may be processed but not recorded as completed. The agent must use a two-phase commit: first, write a pending list of task IDs to a durable log (e.g., a Kafka topic or a PostgreSQL table), and second, update the batch status after all tasks are successfully processed.

A frequent source of confusion is the difference between concurrency and parallelism. The concurrency value in the batch request sets the number of worker threads or processes available to process tasks. However, each task may itself spawn sub-tasks (e.g., API calls, file reads), and these sub-tasks may be processed in parallel across multiple worker nodes. The agent must track both levels of concurrency.

A subtle failure occurs when tasks are idempotent but not retryable. The agent assumes that a task can be retried multiple times without side effects, but the input data is not versioned. If the task modifies a database table and the same task is processed twice with slightly different input data, the second run overwrites the first, and changes are lost. To fix this, the agent must include a task_version field in the input, and the task processor must verify that the current version matches the expected version before applying updates.

Task Scheduling and Triggering

Batches are triggered either manually or via scheduling. The agent supports two scheduling mechanisms: cron-style and event-driven.

For cron-based scheduling, the agent supports a schedule object in the batch definition:

{
  "schedule": {
    "type": "cron",
    "cron_expression": "0 3 * * *",  // Daily at 3:00 AM UTC
    "timezone": "UTC",
    "start_at": "2024-06-17T00:00:00Z",
    "end_at": "2025-12-31T23:59:59Z"
  }
}

The agent evaluates the cron expression every minute and queues a new batch job if the current time matches. The start_at and end_at fields allow the agent to pause and resume the schedule.

For event-driven triggering, the agent listens to a message queue (e.g., Apache Kafka, AWS SQS) and starts a new batch when a trigger event arrives. The event format is a JSON object with a trigger_type and payload:

{
  "trigger_type": "data-ingestion-completed",
  "payload": {
    "dataset_id": "sales-2024-05",
    "source": "s3://raw-data/sales/2024-05/",
    "record_count": 147321,
    "timestamp": "2024-06-16T22:34:12Z"
  }
}

The agent creates a batch job with the payload as its input_data and metadata extracted from the trigger_type.

Data Flow and Input Management

Each batch task must receive structured input data. The agent expects input data to be a flat list of objects, each with a unique id and a data field. The agent does not enforce a schema but relies on the task processor to validate it.

Input data may be stored in external systems and referenced by URI. The agent supports three input formats:

{
  "input_data_uri": "s3://batch-inputs/user-profiles/2024-06-17.json",
  "input_format": "json",
  "input_schema": {
    "type": "object",
    "properties": {
      "id": { "type": "string" },
      "email": { "type": "string", "format": "email" },
      "signup_timestamp": { "type": "string", "format": "date-time" }
    },
    "required": ["id", "email"]
  }
}

The agent downloads the input data and validates it against the schema before starting the batch. If validation fails, the batch status becomes validation_failed, and the error details are returned:

{
  "error_code": "schema_validation_failed",
  "message": "Input data failed schema validation",
  "details": [
    {
      "path": "/input_data/123/email",
      "error": "Invalid email format",
      "value": "[email protected]"
    },
    {
      "path": "/input_data/123/signup_timestamp",
      "error": "Missing required field",
      "value": null
    }
  ]
}

The agent supports incremental batch processing through the resume_from field. When a batch is resumed, the agent reads the task_id from a previous batch and starts processing tasks from that point, skipping already completed ones. The agent tracks the last_completed_task_id in a database table and uses it to determine the offset.

Output and Result Aggregation

After processing, the agent writes results to a designated output location. The output format is specified in the batch configuration:

{
  "output": {
    "type": "s3",
    "bucket": "batch-results",
    "prefix": "user-profiles/enriched/2024-06-17/",
    "format": "parquet",
    "partition_by": ["region", "year"],
    "compression": "snappy"
  }
}

The agent writes each task’s result as a row in a Parquet file, partitioned by region and year, compressed with Snappy. The output is written in chunks, and the agent updates the batch status as chunks are written.

Results are also available via an API endpoint: GET /api/batches/{batch_id}/results. The response is paginated and includes the full result object for each task:

{
  "batch_id": "batch-9c3f1a7d",
  "results": [
    {
      "task_id": "user-1042",
      "status": "completed",
      "output": {
        "location": {
          "city": "New York",
          "state": "NY",
          "country": "USA",
          "latitude": 40.7128,
          "longitude": -74.0060
        },
        "social_profile": {
          "twitter": "@alice",
          "linkedin": "in/alice",
          "followers": 2147
        },
        "processed_at": "2024-06-17T01:34:22Z"
      },
      "execution_time_ms": 412,
      "error": null
    }
  ],
  "next_page_token": "token-abc123",
  "total_results": 124000
}

The agent supports result aggregation—combining individual task outputs into a summary. Aggregation is configured with a summary object:

{
  "summary": {
    "aggregations": [
      {
        "field": "location.country",
        "operation": "count",
        "alias": "country_count"
      },
      {
        "field": "social_profile.followers",
        "operation": "avg",
        "alias": "avg_followers"
      },
      {
        "field": "processed_at",
        "operation": "max",
        "alias": "latest_processing"
      }
    ],
    "output": {
      "type": "database",
      "table": "batch_summaries",
      "schema": "analytics"
    }
  }
}

The agent runs a SQL query after all tasks are completed, writes the summary to the database, and updates the batch status to summary_completed.

Error Handling and Retry Strategies

The agent applies a default retry strategy: each task is retried up to 3 times, with exponential backoff (1s, 2s, 4s) between attempts. The retry strategy is configurable:

{
  "retry": {
    "max_attempts": 5,
    "backoff": {
      "type": "exponential",
      "initial_delay_ms": 1000,
      "multiplier": 1.5,
      "max_delay_ms": 10000
    },
    "retry_on": [
      "network_timeout",
      "service_unavailable",
      "internal_error"
    ],
    "skip_on": [
      "invalid_input",
      "data_not_found"
    ]
  }
}

Tasks that fail with invalid_input are not retried and are marked as final_failed.

The agent logs all task-level errors to a structured error log table with the following schema:

task_idbatch_iderror_codemessagedetailsretry_countlast_attempt_at
user-1042batch-9c3f1a7dnetwork_timeoutFailed to fetch location data{"url":"https://geo.example.com/v1/coordinates?address=New+York", "timeout_ms":5000}32024-06-17T01:34:45Z

The agent uses this log to identify recurring failures and to trigger alerts.

Resource and Performance Tuning

The agent supports dynamic resource allocation based on batch size and workload. For large batches, the agent can spin up additional worker nodes via Kubernetes:

{
  "resources": {
    "cpu_request": "2",
    "memory_request": "8Gi",
    "node_selector": {
      "agent.pool": "high-performance"
    },
    "tolerations": [
      {
        "key": "agent-type",
        "operator": "Equal",
        "value": "batch",
        "effect": "NoSchedule"
      }
    ]
  }
}

Workers pull tasks from a shared queue (e.g., Redis or Kafka) and update their status in real time. The agent uses the progress object to track throughput and latency.

The agent also supports batch-level resource limits:

When the system exceeds the throttle rate, the agent queues new tasks and delays their start.

Final State and Cleanup

When a batch completes, the agent performs a final cleanup phase. It:

  1. Archives the input data and output files to a long-term storage tier (e.g., S3 Glacier).
  2. Sends a completion webhook to a webhook_url specified in the batch config.
  3. Updates the batch status to completed and writes a summary to a metadata store.

The final status includes a summary field with high-level statistics:

{
  "batch_id": "batch-9c3f1a7d",
  "status": "completed",
  "summary": {
    "total_tasks": 124000,
    "completed": 123822,
    "failed": 178,
    "success_rate": 0.99856,
    "total_duration_seconds": 18724,
    "avg_task_duration_seconds": 0.423,
    "peak_memory_mb": 1280,
    "total_cost_usd": 43.21
  }
}

The agent may also trigger the next batch in a pipeline by setting next_batch_template:

{
  "next_batch_template": {
    "name": "user-profile-analysis-{batch_id}",
    "task_type": "analyze-user-behavior",
    "input_data_uri": "s3://batch-results/user-profiles/enriched/{batch_id}/",
    "schedule": {
      "type": "cron",
      "cron_expression": "0 4 * * *"
    }
  }
}

The agent creates a new batch based on the template and schedules it to run the next day.

This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.