Portfolio Manager DB Agent — Portfolio Case Study
portfolio — containerized backend service
Portfolio Manager DB Agent
A dedicated database worker over WebSocket.
A lightweight, containerized Python service that decouples database access from application logic — connecting a portfolio management backend to MongoDB through a persistent WebSocket channel with automatic reconnection and parallel query execution.
Python 3.12
asyncio
WebSockets
PyMongo
MongoDB
Docker
Docker Compose
overview
Rather than embedding MongoDB access directly into a portfolio management service, this agent externalizes it — running as a separate, independently deployable container. The main service sends JSON commands over a WebSocket; the agent executes the corresponding queries and returns structured results over the same live connection. Multiple agents can run simultaneously from the same image, each connected to a different user, database, or data source.
command flow
Portfolio manager service
Sends a JSON command (e.g. get_portfolio or analyze_portfolio) over the open WebSocket connection.
DB agent receives and dispatches
Parses the command, identifies the action, and routes to the appropriate MongoDB query handler — running blocking calls in an executor to keep the async event loop free.
MongoDB query execution
Queries portfolio, trades, and/or equities collections — in parallel for analysis requests — with connection pooling and timeout controls.
JSON response returned over WebSocket
Results serialized with ObjectId-safe conversion and sent back to the portfolio manager over the same persistent connection.
supported commands
get_portfolio
Retrieves matching portfolio documents from MongoDB for the requesting agent's user context.
portfolio
analyze_portfolio
Runs parallel reads across three collections and returns aggregated data for live portfolio analysis workflows.
portfoliotradesequities
resilience design
MongoDB startup wait
Agent waits for MongoDB to be reachable before connecting to the WebSocket server — prevents failed starts in container orchestration environments.
Exponential backoff
Both MongoDB connection failures and WebSocket disconnects trigger automatic retry with exponential backoff — keeping the agent alive under transient failures.
Executor offloading
Blocking PyMongo calls run in a thread pool executor so the asyncio event loop stays responsive during database I/O.
Connection pooling
PyMongo configured with pooling and timeout settings for more predictable database behavior under sustained query load.
multi-agent Docker Compose
Same imageBoth agent containers run from the same Python Docker image — configuration is entirely environment-driven, keeping the image generic and reusable.
Isolated agentsEach container gets its own AGENT_ID and USER_ID, allowing each to connect to a different MongoDB instance or represent a different user's data source.
Independent restartAgents can be restarted, scaled, or reconfigured without touching the main portfolio service — clean separation of concerns at the infrastructure level.
implementation highlights
01Designed the agent as a dedicated service boundary — the main application stays free of database access logic and communicates purely through JSON commands over WebSocket, making both sides independently testable and deployable.
02Offloaded all blocking PyMongo calls to a thread pool executor — a necessary pattern when mixing synchronous database drivers with an asyncio event loop to avoid blocking the entire agent on a slow query.
03Implemented parallel collection reads for analyze_portfolio — trades, equities, and portfolio documents are fetched concurrently rather than sequentially, reducing latency on analysis requests.
04Built the Docker Compose setup so multiple agents run from a single image with environment-based identity — meaning scaling to additional users or data sources requires only a new Compose entry, not a new codebase.
related project
Companion to Live Stock Performance Platform. This agent is the database worker counterpart to the Live Stock Performance backend — which handles WebSocket agent management, Redis presence tracking, REST APIs, and portfolio analytics. Together they form a complete two-layer system: the platform orchestrates, the agent queries.
full tech stack
Python 3.12asynciowebsocketsPyMongoMongoDBDockerDocker Compose