PostgreSQL patterns for Python with psycopg and asyncpg — connection pooling,
99
99%
Does it follow best practices?
Impact
99%
1.15xAverage score across 5 eval scenarios
Passed
No known issues
An e-commerce company needs a reporting backend for their internal analytics dashboard. The backend is built with Python and PostgreSQL and serves data to a React frontend. The reports involve aggregating large amounts of order data.
The PostgreSQL database has these tables:
customers -- id, email, name, segment (new/returning/vip), region, created_atorders -- id, customer_id (FK), status (pending/confirmed/shipped/delivered/cancelled), total_cents, currency, placed_at, updated_atorder_items -- id, order_id (FK), product_id (FK), quantity, unit_price_cents, created_atproducts -- id, name, category, sku (unique), cost_cents, created_atThe backend needs these report functions:
Revenue by region -- For a given date range, calculate total revenue (sum of order totals for delivered orders) grouped by customer region. This query joins customers and orders and uses aggregation.
Product performance -- For a given date range, return each product with its total units sold, total revenue, and profit margin (revenue minus cost). Include products with zero sales. Sort by revenue descending.
Customer cohort export -- Export all customers who placed their first order in a given month, along with how many orders they placed total and their lifetime spend. The company has 2 million customers, so this must stream results, not load them all into memory.
Daily order sync -- Receive a batch of order updates from the fulfillment system (500-2000 records). Each record has an order ID and a new status. Update all orders to their new status and record the updated_at timestamp. All updates in a batch must succeed or fail together.
The application uses a mix of psycopg 3 (sync) for the report queries (run by background workers) and asyncpg for the API endpoints. Both need proper connection management.
Produce:
app/db.py -- Both sync (psycopg) and async (asyncpg) pool setupapp/reports.py -- The three report functions using psycopg (sync)app/api.py -- The order sync endpoint using asyncpg (async)app/main.py -- Application with lifecycle management for both poolsevals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
skills
postgresql-python-best-practices