โ— LIVE
OpenAI releases GPT-5 APIIndia AI startup raises $120MBitcoin ETF hits record inflowsMeta Llama 4 benchmarks leakedOpenAI releases GPT-5 APIIndia AI startup raises $120MBitcoin ETF hits record inflowsMeta Llama 4 benchmarks leaked
๐Ÿ“… Sat, 21 Mar, 2026โœˆ๏ธ Telegram
AiFeed24

AI & Tech News

๐Ÿ”
โœˆ๏ธ Follow
๐Ÿ Home๐Ÿค–AI๐Ÿ’ปTech๐Ÿš€Startupsโ‚ฟCrypto๐Ÿ”’Security๐Ÿ‡ฎ๐Ÿ‡ณIndiaโ˜๏ธCloud๐Ÿ”ฅDeals
โœˆ๏ธ News Channel๐Ÿ›’ Deals Channel
API Response Optimization
โ˜๏ธCloud & DevOps

API Response Optimization

Home/Cloud & DevOps/API Response Optimization

In the early days of a startup, functional is the goal. You write a query, you get the data, and you send it to the frontend. But as we scaled past 50,000 users, that functional code became a massive liability. We realized that frontend performance means nothing if your backend is bloated. When ever

โšกQuick SummaryAI generating...
G

Gavin Hemsada

๐Ÿ“… Mar 21, 2026ยทโฑ 5 min readยทDev.to โ†—
โœˆ๏ธ Telegram๐• TweetWhatsApp
๐Ÿ“ก

Original Source

Dev.to

https://dev.to/gavin_hemsada_e40424b9d48/api-response-optimization-7de
Read Full โ†—

In the early days of a startup, functional is the goal. You write a query, you get the data, and you send it to the frontend. But as we scaled past 50,000 users, that functional code became a massive liability. We realized that frontend performance means nothing if your backend is bloated. When every millisecond counts, your API response strategy is the difference between a smooth user experience and a hanging loading spinner.

The Invisible Cost of SELECT

The most common mistake Node.js developers make is over-fetching. We often use SELECT * or return entire Mongoose documents because itโ€™s easier. However, at scale, this is devastating. Every extra field you send adds to the payload size, which increases network latency. More importantly, it increases the time the Node.js process spends on JSON serialization.

Converting a massive object into a JSON string is a CPU-intensive, synchronous operation. If your CPU is busy stringifying a 2MB response for User A, User Bโ€™s request is sitting in the event loop queue, waiting. We solved this by implementing strict Data Transfer Objects (DTOs). If the mobile app only needs the username and profile_pic, that is all the SQL query should fetch. This reduced our internal bus traffic and slashed response times by 30%.

Master the Event Loop

Node.js is single-threaded. This is its greatest strength and its primary weakness. To scale to 50K users, you must treat the Event Loop as a sacred resource. Any synchronous logic like heavy data transformation, complex regex on large strings, or fs.readSync will block the loop.

When the loop is blocked, the server is effectively dead to all other users. We audited our code to ensure that all heavy lifting was either moved to a background worker (like BullMQ) or handled using asynchronous patterns. We also utilized setImmediate() to break up long-running loops into smaller chunks, allowing the event loop to breathe and process incoming I/O between iterations.

Compression: Gzip vs. Brotli

Finally, never send raw text. We implemented the compression middleware in Express, but we took it a step further by favoring Brotli over Gzip for supported browsers. Brotli offers better compression ratios for text-based assets like JSON.

By compressing our responses, we reduced our bandwidth costs significantly. However, remember that compression itself costs CPU cycles. The sweet spot we found was setting a threshold (e.g., only compress responses larger than 1KB) to ensure we weren't wasting CPU power on tiny payloads where the overhead of compression outweighed the savings.

This sample demonstrates how to use Brotli/Gzip compression, DTOs (Data Transfer Objects) to prevent over-fetching, and how to keep the Event Loop clear.

const express = require('express');
const compression = require('compression');
const app = express();

// 1. Implement Compression (Prioritizing Brotli for efficiency)
app.use(compression({
  level: 6, // Balance between CPU usage and compression ratio
  threshold: 1024, // Only compress responses larger than 1KB
  filter: (req, res) => {
    if (req.headers['x-no-compression']) return false;
    return compression.filter(req, res);
  }
}));

// 2. Data Transfer Object (DTO) Logic
// Avoid 'SELECT *'. Only return what the client needs.
const formatUserResponse = (user) => ({
  id: user.id,
  username: user.username,
  avatar: user.profile_image_url,
  memberSince: user.created_at
});

app.get('/api/users/:id', async (req, res) => {
  try {
    const userId = req.params.id;

    // Simulate DB call - specifically selecting fields at the query level
    const user = await db.user.findUnique({
      where: { id: userId },
      select: { id: true, username: true, profile_image_url: true, created_at: true }
    });

    if (!user) return res.status(404).json({ error: 'User not found' });

    // 3. Non-blocking processing
    // If you have heavy logic, use setImmediate to let the Event Loop breathe
    setImmediate(() => {
      console.log(`Log: Profile accessed for user ${userId}`);
    });

    res.json(formatUserResponse(user));
  } catch (err) {
    res.status(500).send('Server Error');
  }
});

Tags:#cloud#dev.to

Found this useful? Share it!

โœˆ๏ธ Telegram๐• TweetWhatsApp

Read the Full Story

Continue reading on Dev.to

Visit Dev.to โ†—

Related Stories

โ˜๏ธ
โ˜๏ธCloud & DevOps

Majority Element

about 2 hours ago

โ˜๏ธ
โ˜๏ธCloud & DevOps

Building a SQL Tokenizer and Formatter From Scratch โ€” Supporting 6 Dialects

about 2 hours ago

โ˜๏ธ
โ˜๏ธCloud & DevOps

Markdown Knowledge Graph for Humans and Agents

about 2 hours ago

Moving Beyond Disk: How Redis Supercharges Your App Performance
โ˜๏ธCloud & DevOps

Moving Beyond Disk: How Redis Supercharges Your App Performance

about 2 hours ago

๐Ÿ“ก Source Details

Dev.to

๐Ÿ“… Mar 21, 2026

๐Ÿ• about 3 hours ago

โฑ 5 min read

๐Ÿ—‚ Cloud & DevOps

Read Original โ†—

Web Hosting

๐ŸŒ Hostinger โ€” 80% Off Hosting

Start your website for โ‚น69/mo. Free domain + SSL included.

Claim Deal โ†’

๐Ÿ“ฌ AiFeed24 Daily

Top 5 AI & tech stories every morning. Join 40,000+ readers.

โœฆ 40,218 subscribers ยท No spam, ever

Cloud Hosting

โ˜๏ธ Vultr โ€” $100 Free Credit

Deploy cloud servers in 25+ locations. From $2.50/mo. No contract.

Claim $100 Credit โ†’
AiFeed24

India's AI-powered tech news hub. Daily coverage of AI, startups, crypto and emerging technology.

โœˆ๏ธ๐Ÿ›’

Topics

Artificial IntelligenceStartups & VCCryptocurrencyCybersecurityCloud & DevOpsIndia Tech

Company

About AiFeed24Write For UsContact

Daily Digest

Top 5 AI stories every morning. 40,000+ readers.

No spam, ever.

ยฉ 2026 AiFeed24 Media.Affiliate Disclosure โ€” We earn commission on qualifying purchases at no extra cost to you.
PrivacyTermsCookies