10 Proven Strategies to Supercharge API Performance in Java Applications
This article presents a comprehensive set of practical techniques—including batch processing, asynchronous execution, caching, preprocessing, pooling, parallelization, indexing, pagination, SQL tuning, and lock granularity—to dramatically reduce API latency and improve overall backend system efficiency.
1. Background
For an old project, many cost‑reduction and efficiency‑boosting efforts were made last year, and the most frequent issue discovered was excessive interface latency, prompting a focused API performance optimization effort.
2. Interface Optimization Summary
1. Batch Processing
Batch thinking: perform bulk database operations. In loops that insert records one by one, replace them with a single batch insert or update to avoid repeated I/O.
// for‑loop single insert
list.stream().forEach(msg -> {
insert();
});
// batch insert
batchInsert();2. Asynchronous Processing
Asynchronous thinking: for time‑consuming logic that does not need an immediate result, move it to asynchronous execution to reduce interface latency.
For example, in a financial product subscription interface, the accounting and file‑writing steps are synchronous but not required in real time, so they can be handled asynchronously.
Implementation can use thread pools, message queues, or scheduling frameworks.
3. Space‑for‑Time (Caching)
A classic space‑for‑time example is reasonable caching: frequently accessed but rarely changed data can be cached to avoid repeated database queries or calculations.
Note that caching is a double‑edged sword; consider data consistency issues.
Caches can be R2M, local cache, Memcached, or simple Maps.
Example: a stock tool updates rotation information weekly; caching the database query and computation results saves a lot of time.
4. Preprocessing
Pre‑fetching means calculating data in advance and storing it in cache or a table column, dramatically improving interface performance when the data is needed.
Example: a financial product’s annualized return can be pre‑computed from its net value, allowing the interface to simply read the stored field.
5. Pooling Concept
Database connection pools, thread pools, etc., embody pooling: they avoid repeatedly creating objects or connections, reusing them instead to save time.
The essence of pooling is pre‑allocation and cyclic reuse, which can be applied to many business scenarios.
6. Serial to Parallel
Serial execution waits for the previous step to finish; parallel execution runs independent tasks concurrently, greatly reducing total time when there are no result dependencies.
For a portfolio display interface, querying account info, product info, and banner data in parallel cuts latency compared to sequential calls.
7. Index
Adding indexes can dramatically improve query efficiency; this should be considered during interface design.
8. Avoid Large Transactions
Large transactions—long‑running transactions that hold database connections—can cause lock contention and degrade performance.
@Transactional(value="taskTransactionManager", propagation=Propagation.REQUIRED, isolation=Isolation.READ_COMMITTED, rollbackFor={RuntimeException.class, Exception.class})
public BasicResult purchaseRequest(PurchaseRecord record){
BasicResult result = new BasicResult();
// insert account task
taskMapper.insert(ManagerParamUtil.buildTask(record, TaskEnum.Task_type.pension_account.type(), TaskEnum.Account_bizType.purchase_request.type()));
// insert sync task
taskMapper.insert(ManagerParamUtil.buildTask(record, TaskEnum.Task_type.pension_sync.type(), TaskEnum.Sync_bizType.purchase.type()));
// insert image upload task
taskMapper.insert(ManagerParamUtil.buildTask(record, TaskEnum.Task_type.pension_sync.type(), TaskEnum.Sync_bizType.cert.type()));
result.setInfo(ResultInfoEnum.SUCCESS);
return result;
}If RPC calls (e.g., push notifications) are placed inside the transaction, they can cause large‑transaction problems.
@Transactional(value="taskTransactionManager", propagation=Propagation.REQUIRED, isolation=Isolation.READ_COMMITTED, rollbackFor={RuntimeException.class, Exception.class})
public BasicResult purchaseRequest(PurchaseRecord record){
BasicResult result = new BasicResult();
// ... other logic ...
pushRpc.doPush(record);
result.setInfo(ResultInfoEnum.SUCCESS);
return result;
}Mitigation steps:
Do not place RPC calls inside transactions.
Keep query operations outside transactions when possible.
Avoid processing excessive data within a transaction.
9. Optimize Program Structure
Repeated iterations and feature additions can lead to tangled code, duplicate queries, and unnecessary object creation. Refactor the interface code, evaluate each block’s purpose, and reorder execution to improve performance.
10. Deep Pagination Issue
Using LIMIT 100000,200 forces the database to scan over 100,200 rows, discarding the first 100,000, which is slow.
select * from purchase_record where productCode='PA9044' and status=4 order by orderTime desc limit 100000,200;A better approach is to use a primary‑key condition to leverage the index:
select * from purchase_record where productCode='PA9044' and status=4 and id > 100000 limit 200;This requires a continuously increasing ID column but yields consistent performance.
11. SQL Optimization
SQL tuning—using indexes, proper pagination, and other techniques—can greatly improve query performance; readers should combine these ideas with the earlier suggestions.
12. Lock Granularity
Locks protect shared resources in high‑concurrency scenarios, but overly coarse locks hurt performance.
Only lock the critical section of shared resources, not unrelated code.
// wrong locking
synchronized(this){
share();
notShare();
}
// correct locking
notShare();
synchronized(this){
share();
}3. Conclusion
Interface performance problems usually accumulate over multiple iterations of rapid feature delivery; adopting higher‑level thinking and designing from the perspective of an API designer can prevent many of these issues and is an effective way to reduce cost and increase efficiency.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
