API Development and Integration

Master RESTful API design, GraphQL, API security, documentation, and integration patterns.

advanced Backend Development 6 hours

Chapter 12: API Performance

Chapter 12 of 14

Chapter 12: API Performance

12.1 Optimization

API performance directly impacts user experience and server costs.

Caching Strategies:

// Response caching
const cache = require('memory-cache');

app.get('/api/users/:id', async (req, res) => {
    const cacheKey = `user:${req.params.id}`;
    const cached = cache.get(cacheKey);
    
    if (cached) {
        return res.json(cached);
    }
    
    const user = await User.findById(req.params.id);
    cache.put(cacheKey, user, 60000); // Cache for 1 minute
    res.json(user);
});

// Redis caching
const redis = require('redis');
const client = redis.createClient();

async function getCachedUser(userId) {
    const cached = await client.get(`user:${userId}`);
    if (cached) return JSON.parse(cached);
    
    const user = await User.findById(userId);
    await client.setEx(`user:${userId}`, 3600, JSON.stringify(user));
    return user;
}

12.2 Pagination

// Cursor-based pagination (better for large datasets)
app.get('/api/users', async (req, res) => {
    const { cursor, limit = 10 } = req.query;
    
    const query = cursor ? { _id: { $gt: cursor } } : {};
    const users = await User.find(query)
        .limit(parseInt(limit) + 1)
        .sort({ _id: 1 });
    
    const hasMore = users.length > limit;
    const data = hasMore ? users.slice(0, -1) : users;
    const nextCursor = hasMore ? data[data.length - 1]._id : null;
    
    res.json({
        data,
        pagination: {
            hasMore,
            nextCursor
        }
    });
});

12.3 Compression

// Enable compression
const compression = require('compression');
app.use(compression());