API Optimization — Complete Guide
API Optimization — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MEAN Stack Tutorial on Toolliyo Academy.
On this page
MEAN Stack Tutorial · Lesson 75 of 100
API Optimization
Stack ✓ → Projects
Projects · 2 — Apps · ~10 min · MEAN — Performance & Testing
What is this?
API optimization improves Express response time via compression, pagination, caching headers, and efficient Mongo projections.
Why should you care?
Angular makes many parallel calls — slow APIs multiply into frozen UI.
See it live — copy this example
Paste into your MeanVerse project (Angular + Express + MongoDB), then run with ng serve / node / mongosh as noted.
import compression from 'compression';
app.use(compression());
app.get('/api/v1/accounts', auth, async (req, res) => {
const page = Math.max(1, Number(req.query.page) || 1);
const limit = Math.min(100, Number(req.query.limit) || 20);
const filter = { tenantId: req.user.tenantId };
const [items, total] = await Promise.all([
Account.find(filter).select('name balanceCents').skip((page - 1) * limit).limit(limit).lean(),
Account.countDocuments(filter)
]);
res.set('Cache-Control', 'private, max-age=10');
res.json({ items, total, page, limit });
});
What happened?
- compression gzip JSON bodies.
- Parallel find + count with Promise.all.
- select + lean minimizes payload.
- Cache-Control hints browser/CDN for brief private cache.
Practice next
- Add compression middleware globally.
- Paginate all list endpoints with max limit cap.
- Return ETag for conditional GET on static config.
- Add cursor-based pagination for infinite scroll.
- Enable HTTP/2 behind Nginx for multiplexing.
Remember
Compress, paginate, project, parallelize. Set cache headers where safe. Measure p95 with APM tools.
Mobile account list
App scrolled infinite list; offset pagination slow at page 500.
Outcome: Cursor pagination by _id keeps constant time per page.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!