Article · 2022-03-24

Practical API Service Performance Optimization

Optimization Strategy

We implemented the following approaches:

View Aggregation and Batch Querying

CREATE OR REPLACE VIEW vw_resource_full AS
SELECT b.resource_id,
       b.name,
       m.category,
       e.score,
       ...
FROM   resource_basic b
JOIN   resource_meta m   ON m.resource_id = b.resource_id
LEFT JOIN resource_extra e ON e.resource_id = b.resource_id
WHERE  b.status = 'ACTIVE';

Order Correction

id_list = compute_ids_by_range(params)        # 原始顺序
rows = db.select_many(
    """SELECT * FROM vw_resource_full WHERE resource_id IN %(ids)s""",
    {'ids': tuple(id_list)}
)
row_map = {row['resource_id']: row for row in rows}
result = [row_map[rid] for rid in id_list if rid in row_map]

Sorting Logic Simplification

The optimized implementation retrieves data through a single SQL query including all IDs, dramatically reducing database interactions. Query results are then ordered according to the original ID list, replacing the previous custom sorting process. When business requirements call for sorting by a specific field, this can be completed directly with an ORDER BY clause in the database query, avoiding application-layer loop sorting overhead.

Performance Verification

Metric Before After
Average Response Time 800–1200 ms 90–120 ms
Database Query Count N+1 1
99th Percentile Latency >2 s <300 ms

After optimization, we verified interface performance by comparing logs from test environments and monitoring data from production tools. Response times showed marked improvements:

These metrics confirm the optimization achieved its intended effect: improved interface performance while maintaining functional correctness.

Key Lessons

© 2026 Yuxu Ge ·