10 Proven Strategies to Supercharge API Performance in Java Backend
Discover a comprehensive set of practical techniques—including batch processing, asynchronous handling, caching, pre‑processing, pooling, parallel execution, indexing, transaction optimization, code refactoring, pagination, and lock granularity—to dramatically reduce API latency and improve backend efficiency, illustrated with Java code examples and diagrams.
1. Background
For an older project, many cost‑reduction and efficiency‑boosting measures were taken last year, and the most frequent issue discovered was excessively long API response times, prompting a focused interface performance optimization effort.
2. Interface Optimization Summary
1. Batch Processing
Batch processing means performing database operations in bulk; for example, instead of inserting records one by one inside a loop, collect them and execute a single batch insert to reduce I/O.
// for‑loop single insert
list.stream().forEach(msg -> {
insert();
});
// batch insert
batchInsert();2. Asynchronous Handling
Asynchronous processing moves time‑consuming, non‑essential logic to background execution, lowering perceived API latency.
Example: a financial purchase interface where accounting and file‑writing are not required in real‑time (T+1 transaction). These steps can be handled asynchronously.
Implementation can use thread pools, message queues, or scheduling frameworks.
3. Space‑for‑Time (Caching)
Using caches for frequently accessed, rarely changed data avoids repeated database queries or calculations, but must consider consistency trade‑offs.
Caches may be Redis, Memcached, local maps, etc.
Example: a stock‑tool query where rotation information updates only weekly; caching the data and computed results saves considerable execution time.
4. Pre‑processing
Pre‑compute data and store it in a cache or dedicated column so that retrieval is fast; e.g., pre‑calculate annualized return from net value for financial products and store the result for direct lookup.
5. Pooling
Reuse objects such as database connections or threads to avoid the overhead of repeated creation; the core idea is pre‑allocation and cyclic reuse.
6. Serial to Parallel
Convert independent sequential steps into parallel execution to reduce total latency. For a portfolio page, fetching account info, product info, and banner data can be done concurrently.
7. Indexing
Adding appropriate indexes dramatically improves query speed; be aware of scenarios where indexes may not be effective.
8. Avoid Large Transactions
Long‑running transactions hold database connections and degrade overall performance. The example below shows a @Transactional method that inserts several tasks; adding non‑DB RPC calls inside the transaction can cause big‑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();
// insert tasks
taskMapper.insert(ManagerParamUtil.buildTask(record, TaskEnum.Task_type.pension_account.type(), TaskEnum.Account_bizType.purchase_request.type()));
taskMapper.insert(ManagerParamUtil.buildTask(record, TaskEnum.Task_type.pension_sync.type(), TaskEnum.Sync_bizType.purchase.type()));
taskMapper.insert(ManagerParamUtil.buildTask(record, TaskEnum.Task_type.pension_sync.type(), TaskEnum.Sync_bizType.cert.type()));
result.setInfo(ResultInfoEnum.SUCCESS);
return result;
}Solutions: keep RPC calls out of the transaction, perform reads outside the transaction, and limit the amount of data processed inside.
9. Refactor Program Structure
Iterative development often leads to tangled code with redundant queries and object creation; refactor by evaluating each block’s purpose, removing duplication, and reordering execution for efficiency.
10. Deep Pagination
Using OFFSET with a large limit scans many rows (e.g., LIMIT 100000,200). Replace with keyset pagination that leverages the primary‑key index.
SELECT * FROM purchase_record WHERE productCode='PA9044' AND status=4 AND id > 100000 LIMIT 200;11. SQL Optimization
General SQL tuning—combined with proper indexing and pagination—further boosts performance.
12. Lock Granularity
Apply fine‑grained locks only around truly shared resources; avoid locking non‑shared code.
// wrong: lock both shared and non‑shared
synchronized(this) {
share();
notShare();
}
// correct: lock only shared part
notShare();
synchronized(this) {
share();
}3. Conclusion
Performance problems usually accumulate over many iterations; adopting higher‑level thinking and designing APIs with the strategies above can significantly reduce latency and improve cost 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.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
