Backend Flashcards
(46 cards)
What is a REST API, and what are its key principles?
A REST API uses HTTP methods (GET, POST, PUT, DELETE) for stateless, resource-based communication. Key principles: statelessness, client-server separation, uniform interface, and resource-based URLs.
How does HTTP differ from HTTPS?
HTTP transfers data in plain text; HTTPS uses SSL/TLS for encrypted, secure communication. HTTPS is critical for protecting sensitive data like passwords.
What is the difference between SQL and NoSQL databases?
SQL databases (e.g., MySQL) are relational, use structured tables, and support SQL queries; NoSQL databases (e.g., MongoDB) are non-relational, flexible, and handle unstructured data.
Write a SQL query to find the second highest salary in a table.
```sql
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
– Explanation: Finds the highest salary excluding the maximum (O(n) scan).
~~~
What is ACID in the context of databases?
ACID ensures reliable database transactions: Atomicity (all or nothing), Consistency (valid state), Isolation (independent transactions), Durability (committed changes persist).
Explain the difference between a primary key and a foreign key.
A primary key uniquely identifies each record in a table; a foreign key links to a primary key in another table to enforce referential integrity.
What is normalization in databases?
Normalization organizes a database to reduce redundancy and improve integrity, using rules like 1NF (no repeating groups), 2NF (no partial dependencies), and 3NF (no transitive dependencies).
How does indexing improve database performance?
Indexing creates a data structure (e.g., B-tree) for faster query lookups, reducing search time from O(n) to O(log n), but increases write time and storage.
What is a JOIN in SQL, and name its types?
A JOIN combines rows from multiple tables based on a condition. Types: INNER (matching rows), LEFT (all left table rows), RIGHT (all right table rows), FULL (all rows).
Write a SQL query to join two tables and get employee names with department names.
```sql
SELECT e.name, d.department_name
FROM employees e
INNER JOIN departments d ON e.department_id = d.id;
– Explanation: Matches employees to departments via department_id (O(n)).
~~~
What is a NoSQL database like MongoDB used for?
MongoDB stores data as JSON-like documents, ideal for unstructured data, scalability, and flexibility in applications like real-time analytics or content management.
How do you handle database connection pooling in a backend application?
Connection pooling reuses database connections to avoid overhead. Example in Node.js: Use pg-pool
for PostgreSQL to manage connections efficiently.
What is middleware in the context of a backend framework like Express?
Middleware are functions that process requests in Express, executed between request and response. Example: app.use((req, res, next) => { console.log(req.url); next(); });
.
Write a Node.js Express route to handle a POST request.
```javascript
const express = require(‘express’);
const app = express();
app.use(express.json());
app.post(‘/users’, (req, res) => {
const { name } = req.body;
res.status(201).json({ id: 1, name });
});
// Example: POST {name: ‘Alice’} to /users → {id: 1, name: ‘Alice’}
// Explanation: Handles JSON payload, returns created resource (O(1)).
~~~
What is JWT, and how is it used for authentication?
JWT (JSON Web Token) is a compact token with header, payload, and signature, used for secure authentication. Example: Verify user identity via Authorization: Bearer <token>
.
How do you implement JWT authentication in Node.js?
```javascript
const jwt = require(‘jsonwebtoken’);
function authenticateToken(req, res, next) {
const token = req.headers[‘authorization’]?.split(‘ ‘)[1];
if (!token) return res.status(401).send(‘Unauthorized’);
jwt.verify(token, ‘secret’, (err, user) => {
if (err) return res.status(403).send(‘Forbidden’);
req.user = user;
next();
});
}
// Explanation: Verifies JWT in header, attaches user to request (O(1)).
~~~
What is CORS, and how do you handle it in a backend?
CORS (Cross-Origin Resource Sharing) controls browser cross-domain requests. In Express: app.use(cors());
allows specific origins to access the API.
What is caching, and how does it improve backend performance?
Caching stores frequently accessed data (e.g., in Redis) to reduce database load. Example: Cache API responses to serve data faster (O(1) lookup).
How does Redis differ from a traditional database?
Redis is an in-memory key-value store for fast access (O(1)), used for caching or sessions, unlike disk-based SQL databases for persistent storage.
What is load balancing, and why is it important?
Load balancing distributes traffic across multiple servers to improve scalability and reliability. Example: Use NGINX to route requests to backend instances.
Explain the difference between synchronous and asynchronous programming in Node.js.
Synchronous code executes sequentially, blocking execution; asynchronous uses callbacks, promises, or async/await for non-blocking I/O. Example: fs.readFileSync
vs. fs.promises.readFile
.
How do you handle errors in a Node.js backend?
```javascript
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: ‘Internal Server Error’ });
});
// Explanation: Global error middleware catches unhandled errors, returns 500 response.
~~~
What is sharding in databases?
Sharding splits a database into smaller, distributed pieces (shards) to improve scalability. Each shard handles a subset of data.
How do you design a rate limiter for an API?
```javascript
const rateLimit = (limit, windowMs) => {
const requests = new Map();
return (req, res, next) => {
const key = req.ip;
const now = Date.now();
if (!requests.has(key)) requests.set(key, []);
requests.set(key, requests.get(key).filter(t => now - t < windowMs));
if (requests.get(key).length >= limit) return res.status(429).send(‘Too Many Requests’);
requests.get(key).push(now);
next();
};
}
// Explanation: Tracks requests per IP in a time window, rejects excess (O(1)).
~~~