|9. API Design आणि Rate Limiting
Chapter 9System Design~1 min read

API Design आणि Rate Limiting

Production-Ready APIs बनवणे

Good API design system design मधला important part आहे. REST API conventions, versioning, pagination, rate limiting — हे सगळं production APIs मध्ये essential आहे.

REST API Design Best Practices

Good REST API conventions

text
# Resources nouns वापरा (verbs नाही)
✅ GET    /users          # सगळे users
✅ GET    /users/123      # specific user
✅ POST   /users          # नवीन user बनवा
✅ PUT    /users/123      # user update करा
✅ DELETE /users/123      # user delete करा

✅ GET    /users/123/orders    # user चे orders
✅ POST   /users/123/orders    # user चा नवीन order

❌ GET    /getUsers       # verb वापरू नका
❌ POST   /createUser     # verb वापरू नका
❌ GET    /deleteUser/123 # GET ने delete नाही

# Versioning
✅ /api/v1/users          # URL versioning — most common
✅ Header: API-Version: 1 # Header versioning

Pagination

Pagination strategies

text
# Offset Pagination (simple, common)
GET /users?page=2&limit=20
Response: { data: [...], total: 1000, page: 2, pages: 50 }

Problem: Large offset slow — OFFSET 10000 = 10000 rows skip करतो

# Cursor-based Pagination (better for large datasets)
GET /users?cursor=eyJpZCI6MTAwfQ==&limit=20
Response: { data: [...], next_cursor: "eyJpZCI6MTIwfQ==" }

Cursor = last item चा encoded ID/timestamp
Fast — INDEX directly जातो
✅ Twitter, Instagram feed cursor-based वापरतात

Rate Limiting

Rate Limiting म्हणजे एका user/IP ला किती requests per second/minute allow करायच्या हे limit करणे. DDoS attacks रोखण्यासाठी आणि fair usage साठी.

  • Token Bucket — N tokens/sec refill, प्रत्येक request एक token वापरतो. Burst allowed.
  • Fixed Window Counter — X requests per minute. Window reset होतो.
  • Sliding Window — rolling window, more accurate.
  • Redis + Lua scripts — distributed rate limiting साठी.
  • HTTP 429 Too Many Requests — rate limit exceeded response.

Rate limiting with express-rate-limit

javascript
const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000,  // 15 minutes
  max: 100,                    // 100 requests per window
  message: { error: 'Too many requests, please try again later.' },
  headers: true,              // X-RateLimit-* headers add करतो
});

app.use('/api/', limiter);   // सगळ्या API routes वर

Key Points — लक्षात ठेवा

  • REST: nouns वापरा, HTTP methods properly
  • Versioning: /api/v1/ — breaking changes साठी
  • Cursor pagination: large datasets साठी
  • Rate Limiting: abuse रोखण्यासाठी
  • HTTP 429: rate limit exceeded
0/11 chapters पूर्ण