Backend Flashcards

(46 cards)

1
Q

What is a REST API, and what are its key principles?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How does HTTP differ from HTTPS?

A

HTTP transfers data in plain text; HTTPS uses SSL/TLS for encrypted, secure communication. HTTPS is critical for protecting sensitive data like passwords.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between SQL and NoSQL databases?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Write a SQL query to find the second highest salary in a table.

A

```sql
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
– Explanation: Finds the highest salary excluding the maximum (O(n) scan).
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is ACID in the context of databases?

A

ACID ensures reliable database transactions: Atomicity (all or nothing), Consistency (valid state), Isolation (independent transactions), Durability (committed changes persist).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Explain the difference between a primary key and a foreign key.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is normalization in databases?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How does indexing improve database performance?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is a JOIN in SQL, and name its types?

A

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Write a SQL query to join two tables and get employee names with department names.

A

```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)).
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is a NoSQL database like MongoDB used for?

A

MongoDB stores data as JSON-like documents, ideal for unstructured data, scalability, and flexibility in applications like real-time analytics or content management.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you handle database connection pooling in a backend application?

A

Connection pooling reuses database connections to avoid overhead. Example in Node.js: Use pg-pool for PostgreSQL to manage connections efficiently.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is middleware in the context of a backend framework like Express?

A

Middleware are functions that process requests in Express, executed between request and response. Example: app.use((req, res, next) => { console.log(req.url); next(); });.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Write a Node.js Express route to handle a POST request.

A

```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)).
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is JWT, and how is it used for authentication?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you implement JWT authentication in Node.js?

A

```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)).
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is CORS, and how do you handle it in a backend?

A

CORS (Cross-Origin Resource Sharing) controls browser cross-domain requests. In Express: app.use(cors()); allows specific origins to access the API.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is caching, and how does it improve backend performance?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How does Redis differ from a traditional database?

A

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.

20
Q

What is load balancing, and why is it important?

A

Load balancing distributes traffic across multiple servers to improve scalability and reliability. Example: Use NGINX to route requests to backend instances.

21
Q

Explain the difference between synchronous and asynchronous programming in Node.js.

A

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.

22
Q

How do you handle errors in a Node.js backend?

A

```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.
~~~

23
Q

What is sharding in databases?

A

Sharding splits a database into smaller, distributed pieces (shards) to improve scalability. Each shard handles a subset of data.

24
Q

How do you design a rate limiter for an API?

A

```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)).
~~~

25
What is the CAP theorem in distributed systems?
CAP theorem states a system can only guarantee two of: Consistency (same data everywhere), Availability (always responds), Partition Tolerance (handles network failures).
26
How do you optimize a slow SQL query?
Analyze with `EXPLAIN`, add indexes on filtered/joined columns, reduce selected columns, and avoid subqueries or use joins instead.
27
What is the purpose of an API gateway?
An API gateway routes requests, handles authentication, rate limiting, and load balancing. Example: AWS API Gateway manages microservices.
28
How do you secure a REST API?
Use HTTPS, JWT for authentication, validate inputs, implement rate limiting, and sanitize data to prevent SQL injection or XSS.
29
What is eventual consistency in NoSQL databases?
Eventual consistency means updates propagate across nodes over time, prioritizing availability over immediate consistency, common in distributed NoSQL systems.
30
Explain microservices architecture.
Microservices split an application into small, independent services communicating via APIs, improving scalability and deployment but increasing complexity.
31
What is Node.js, and why is it used for backend development?
Node.js is a runtime for executing JavaScript outside browsers, using V8. It’s used for backend due to its non-blocking I/O, event-driven architecture, and scalability for real-time apps.
32
How does the Node.js event loop work?
The event loop handles asynchronous tasks by processing the call stack, then the callback queue (e.g., for timers, I/O) when the stack is empty, enabling non-blocking operations.
33
What is the purpose of the `fs` module in Node.js?
The `fs` (File System) module handles file operations like reading/writing. Example: `const fs = require('fs'); fs.readFile('file.txt', 'utf8', (err, data) => console.log(data));` (O(n)).
34
How do you create a simple HTTP server in Node.js?
```javascript const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello, World!'); }); server.listen(3000, () => console.log('Server running on port 3000')); // Explanation: Creates a server responding with 'Hello, World!' on port 3000 (O(1)). ```
35
What is the difference between `process.nextTick` and `setImmediate`?
`process.nextTick` queues a callback before the next event loop phase, with higher priority; `setImmediate` schedules it after I/O events, in the check phase.
36
How do you handle asynchronous errors in Node.js?
```javascript async function fetchData() { try { const data = await someAsyncFunction(); return data; } catch (err) { console.error('Error:', err.message); throw err; } } // Explanation: Use try/catch with async/await or `.catch()` with Promises to handle errors gracefully. ```
37
What is the `cluster` module in Node.js, and how does it improve performance?
The `cluster` module enables multi-core processing by forking worker processes. Example: `const cluster = require('cluster'); if (cluster.isMaster) { cluster.fork(); }` distributes load.
38
How do you implement streaming in Node.js for large files?
```javascript const fs = require('fs'); const server = require('http').createServer((req, res) => { const stream = fs.createReadStream('large.txt'); stream.pipe(res); }); server.listen(3000); // Explanation: Streams data in chunks, reducing memory usage for large files (O(n)). ```
39
What is the purpose of `module.exports` in Node.js?
`module.exports` defines what a module exposes. Example: `module.exports = { add: (a, b) => a + b };` allows importing the `add` function in another file.
40
How do you prevent callback hell in Node.js?
Use Promises or async/await to flatten asynchronous code. Example: `async function run() { const data1 = await task1(); const data2 = await task2(data1); }` avoids nested callbacks.
41
What is Mongoose, and how do you define a schema for a MongoDB collection?
Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js, simplifying data modeling and querying. A schema defines the structure of documents. Example: ```javascript\nconst mongoose = require('mongoose');\nconst userSchema = new mongoose.Schema({\n name: { type: String, required: true },\n email: { type: String, unique: true }\n});\nconst User = mongoose.model('User', userSchema);\n``` Explanation: Creates a User model with name and email fields, enforcing constraints like uniqueness (O(1) schema setup).
42
How do you perform a query with Mongoose to find and update a document?
Use Mongoose’s `findOneAndUpdate` to query and update a document. Example: ```javascript\nUser.findOneAndUpdate(\n { email: 'user@example.com' },\n { $set: { name: 'New Name' } },\n { new: true }\n).then(user => console.log(user));\n``` Explanation: Finds a user by email, updates their name, returns the updated document. `new: true` ensures the updated document is returned (O(1) query with index).
43
What is Mongoose middleware, and how do you use it to hash passwords before saving?
Mongoose middleware (hooks) runs functions before/after events like save. Example: ```javascript\nconst bcrypt = require('bcrypt');\nuserSchema.pre('save', async function(next) {\n if (this.isModified('password')) {\n this.password = await bcrypt.hash(this.password, 10);\n }\n next();\n});\n``` Explanation: Hashes password before saving a user document if modified, ensuring security (O(1) middleware execution).
44
What is an ODM in the context of backend development?
An ODM (Object Data Modeling) is a library that maps objects in code to documents in a NoSQL database, like MongoDB, simplifying data interactions. Example: Mongoose is an ODM for Node.js, allowing you to define schemas and query MongoDB using JavaScript objects. It abstracts low-level database operations, improving productivity (O(1) schema setup).
45
What is the purpose of an ODM in a backend application?
An ODM simplifies database operations by providing a structured way to define data models, validate data, and perform CRUD operations. It bridges the gap between object-oriented code and NoSQL databases. Example: With Mongoose, you can define a User schema with validation (e.g., required fields) and query like `User.find({ age: { $gt: 18 } })`, reducing boilerplate and errors.
46
How does an ODM like Mongoose differ from an ORM, and why use an ODM for MongoDB?
An ODM (e.g., Mongoose) is for NoSQL databases like MongoDB, mapping JavaScript objects to flexible documents. An ORM (e.g., Sequelize) is for SQL databases, mapping to rigid tables. ODMs suit MongoDB’s schema-less nature, offering features like schema validation and middleware. Example: Mongoose’s `pre('save')` hook can hash passwords before saving, tailored to document-based data (O(1) middleware execution).