Containerized Deployment of AI Agent Systems: Architecture and State Persistence Practices

    This article presents a reusable reference architecture for deploying AI agent applications using two containers and a single shared data volume. It explains how to separate stateless compute from persistent state, how to organize the data layer, how to track model usage costs against subscription quotas, and which four areas must be redesigned when moving from local to cloud deployment. Readers will also find a practical availability and security checklist.

    1. Why Agent Applications Are Hard to Deploy

    The biggest difference between an AI agent application and a traditional web service is that it carries three workloads at once: a user-facing interface, long-running background scheduling logic, and calls to external model services. These three workloads have completely different resource profiles, lifecycles, and failure impacts. Packing them into a single process or a single container makes operations quickly unmanageable.

    The common pain points come down to four:

    • Upgrading the interface forces a restart of the scheduler, interrupting scheduled jobs that are currently running.
    • Session history, skill configuration, and logs are scattered inside the container, so rebuilding the container loses all the data.
    • Costs generated by model calls are opaque, with no accountable view of quota usage.
    • After getting things running locally, moving to the cloud means redoing network egress, storage mounts, and log collection.

    The solution is to fully separate stateless compute from stateful data, and to describe their relationship with declarative orchestration. The sections below lay out a reusable reference architecture.

    2. Reference Architecture: Two Containers Plus One Data Volume

    A proven split is two containers working together with one shared volume:

    • UI container: handles chat interaction, session display, and hosting of frontend static assets. It can be restarted frequently as needs change.
    • Service container: handles model call orchestration, tool execution, and scheduled task dispatch. It requires a stable lifecycle.
    • Shared data volume: mounted at the same path in both containers, holding configuration files, the session database, skill definitions, and runtime logs.

    A representative orchestration description looks like this (it expresses structure only and does not point to any specific product):

    1. services:
    2. webui:
    3. image: your-agent-ui:latest
    4. ports: ["8080:8080"]
    5. volumes: ["./data:/app/data"]
    6. restart: unless-stopped
    7. api:
    8. image: your-agent-core:latest
    9. volumes: ["./data:/app/data"]
    10. restart: unless-stopped
    11. depends_on: [webui]

    The key takeaway is a single sentence: the data lives in the volume, and containers can die at any time. Treating containers as disposable execution units means rebuilding, rolling back, and scaling no longer touch the data layer. This is the prerequisite for automating every later operational action.

    3. Data Layer Design: Consolidating State in One Place

    A shared volume is not just a matter of exposing a directory. You need to plan directory semantics in advance, or the two containers will trample each other. The recommended layout is:

    • Configuration area: model service addresses, quota policies, scheduling intervals, and so on. Usually read-only and consumed by the service container.
    • Session area: conversation history and context indexes. Read and written frequently; an embedded relational or embedded key-value store is recommended to avoid concurrent write conflicts.
    • Skill area: extensible capability definitions and scripts, loaded at directory granularity to make canary rollouts easier.
    • Log area: split by day. The UI container only reads for display, while the service container appends writes.

    Three engineering constraints must be followed. First, only one container should have write permission for a given subdirectory, and directories shared across containers should be mounted read-only. Second, the session store should enable write-ahead logging and periodic snapshots, with snapshot files kept in a separate directory from the database files so a backup never captures an inconsistent state. Third, the volume must be included in the backup strategy: use scheduled jobs to package it locally, and in the cloud prefer managed object storage for an off-site copy.

    4. Model Access and Quota Cost Management

    An agent does not produce intelligence on its own; the real expense happens on the model call side. In practice, subscription-based or pay-as-you-go external model services are common, and cost evaluation comes down to three numbers: the monthly quota ceiling included in the plan, the actual consumption ratio, and the equivalent value converted at list price.

    The original document gives a typical positive example: a subscription tier costing about ten dollars per month had a monthly quota ceiling equivalent to about seventy-two dollars; within three weeks, nineteen percent of the ceiling was consumed, equivalent to about nineteen dollars of list-price usage, for an actual payment of ten dollars. This kind of calculation can be abstracted into a general formula:

    1. # Illustrates cost conversion logic only
    2. def evaluate_cost(used_ratio, quota_list_price, plan_fee):
    3. equivalent = used_ratio * quota_list_price # list-price equivalent consumption
    4. leverage = equivalent / plan_fee # cost leverage ratio
    5. return round(equivalent, 2), round(leverage, 2)
    6. print(evaluate_cost(0.19, 72, 10)) # (13.68, 1.37)

    It is worth stressing that specific quotas, prices, and conversion ratios vary by provider and plan, so readers should rely on the official documentation for the service they use and not copy someone else’s numbers. What is genuinely reusable is the method: treat “consumption ratio × quota list price ÷ actual payment” as a fixed observation metric, record it weekly, and you can tell whether the current plan is being fully utilized and spot quota bottlenecks early as traffic grows.

    Two more things need to be engineered at the access layer. First, wrap the call egress in a single place so retries, timeouts, rate limiting, and failure fallback are handled centrally, and business code does not depend directly on the shape of external interfaces. Second, assign a separate quota identifier to different tasks so costs can be attributed by scenario.

    5. Four Key Differences When Moving to the Cloud

    Moving from local to cloud keeps the architecture the same, but the following four points must be redesigned.

    Network egress. Outbound access from cloud containers usually requires explicit configuration, involving access control policies, key management, and the principle of least privilege. Model service credentials should not be baked into the image; inject them through environment variables or a key management mechanism, with support for rotation.

    Storage selection. A shared volume works on a single host; multi-replica scenarios need shared file storage, or object storage plus a local cache. If the session store requires concurrent writes from multiple instances, migrate it to a managed relational database and demote the embedded store to a local read-only cache.

    Scheduled task dispatch. With multiple replicas, the scheduler must perform single-instance leader election or use a distributed lock, otherwise the same periodic task runs more than once. One implementation writes a lock record with an expiry time to shared storage; the instance that acquires the lock executes and renews it.

    Observability. Logs and metrics must be shipped off the host: logs go to a managed logging service for search and retention, metrics feed into a monitoring and alerting system, and thresholds are set for call failure rate, quota consumption rate, and task backlog. The UI container and the service container should carry different labels so alerts can be traced to a source.

    6. Availability and Security Checklist

    • Set a restart policy and health checks on every container; rebuild as soon as a probe fails, so the “disposable” assumption holds.
    • Run periodic recovery drills on the data volume; a backup that is never verified is not a backup.
    • Use fixed version tags rather than floating tags for images, so build artifacts are traceable.
    • Run with least privilege; avoid privileged containers unless necessary, and mount directories read-only as needed.
    • Session data may contain sensitive information, so encrypt it both at rest and in transit, and define a clear retention period.
    • Set quota alerts on the cost side and notify in advance when a threshold is reached, avoiding passive rate limiting after an overage.

    7. Summary

    The deployment complexity of an agent system lies not in the model but in state governance and cost governance. Splitting the interface and the scheduler into two containers and consolidating all state into one shared data volume turns containers into replaceable execution units. Continuously observing quota usage with the consumption-ratio and list-price conversion metric makes the value of a subscription plan quantifiable. When moving to the cloud, filling in the four areas of network egress, storage selection, scheduler leader election, and observability lets the architecture land smoothly without a rewrite. Baidu AI Cloud offers corresponding product categories in general capabilities such as container platforms, object storage, logging services, and monitoring and alerting, which can serve as the foundation for the architecture above; refer to the official documentation for specific specifications and pricing.