Backend Developer Interview Questions and Answers
Backend interviews test how you store, process and serve data reliably: language fundamentals, SQL and indexing, concurrency, API design and how systems behave under load.
Intern / Fresher
- What is TypeScript and why do we use it?
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It catches type errors in the editor and at build time, and it documents the shape of data for the next person who reads the code.
- What is the difference between interface and type in TypeScript?
Both describe object shapes. interface can be merged and is preferred for public object contracts; type can express unions, intersections and primitives, and cannot be reopened later.
- What is the difference between INNER JOIN and LEFT JOIN in SQL?
INNER JOIN returns only rows that have a match in both tables, while LEFT JOIN returns every row from the left table and fills the right table's columns with NULL when there is no match.
- What is the difference between WHERE and HAVING in SQL?
WHERE filters individual rows before grouping, while HAVING filters groups after GROUP BY, so only HAVING can use aggregate functions like COUNT or SUM.
- What is the difference between DELETE, TRUNCATE and DROP in SQL?
DELETE removes selected rows and can be rolled back, TRUNCATE quickly removes all rows and keeps the table structure, and DROP removes the entire table including its structure.
- What is the difference between a primary key and a foreign key?
A primary key uniquely identifies each row in its own table and cannot be NULL, while a foreign key is a column that references the primary key of another table to link the two.
- What is the difference between a value type and a reference type in C#?
A value type variable holds its data directly and is copied on assignment, while a reference type variable holds a reference to an object, so assignment copies the reference and both variables see the same object.
- What is the difference between string and StringBuilder in C#?
A string is immutable, so every change creates a new string object, while StringBuilder is a mutable buffer that modifies its contents in place, making it much faster for repeated concatenation.
- What is the difference between JDK, JRE and JVM in Java?
The JVM runs Java bytecode, the JRE is the JVM plus the standard libraries needed to run Java programs, and the JDK is the JRE plus the development tools such as the compiler (javac).
- What is the difference between == and equals() in Java?
== compares primitives by value and objects by reference (whether they are the exact same object), while equals() compares the logical content of two objects when the class overrides it.
- What is the difference between String, StringBuilder and StringBuffer in Java?
String is immutable, StringBuilder is a mutable and fast but not thread-safe buffer, and StringBuffer is a mutable buffer with synchronized methods that is thread-safe but slower.
- What is the difference between final, finally and finalize in Java?
final is a keyword that prevents reassigning a variable, overriding a method or extending a class; finally is a block that always runs after try/catch for cleanup; finalize() was a method called by the garbage collector and is now deprecated.
- What is the difference between a list and a tuple in Python?
A list is mutable and can be changed after creation, while a tuple is immutable; tuples are slightly faster, use less memory and can be used as dictionary keys when their items are hashable.
- What is the difference between is and == in Python?
== checks whether two objects have equal values, while is checks whether they are the exact same object in memory.
- What is Node.js and why is it called single-threaded?
Node.js is a JavaScript runtime built on Chrome's V8 engine that runs your JavaScript on a single main thread and uses non-blocking I/O, so one thread can handle many concurrent connections.
- What is the difference between package.json and package-lock.json?
package.json lists your project's dependencies with allowed version ranges, while package-lock.json records the exact versions that were installed so every machine gets an identical dependency tree.
Junior (0-2 years)
- What is the difference between any, unknown and never in TypeScript?
any turns off checking. unknown is a type-safe any: you must narrow it before use. never means a value cannot exist, used for exhaustive checks and functions that always throw.
- What are generics in TypeScript?
Generics are type parameters: they let a function, class or type work with many types while keeping the relationship between inputs and outputs, instead of falling back to any.
- What are union and intersection types in TypeScript?
A union (A | B) is a value that is one of the members. An intersection (A & B) is a value that must satisfy both types at once.
- What are utility types in TypeScript like Partial, Pick and Omit?
Utility types are built-in helpers that transform an existing type: Partial makes every field optional, Required the opposite, Pick keeps a set of keys, Omit removes them, and Record builds a key/value map.
- How do you find the second highest salary in SQL?
Use a subquery that takes the MAX salary below the overall MAX, or use DENSE_RANK() and pick rank 2, which also handles ties and generalises to the Nth highest.
- How do you find and delete duplicate rows in SQL?
Find duplicates with GROUP BY and HAVING COUNT(*) > 1, then delete them by numbering rows within each duplicate group with ROW_NUMBER() and removing every row after the first.
- What is the difference between UNION and UNION ALL in SQL?
UNION combines two result sets and removes duplicate rows, while UNION ALL combines them and keeps every row, which makes it faster.
- What is database normalization and what are the normal forms?
Normalization is organising tables to reduce redundancy and update anomalies: 1NF means atomic values, 2NF removes partial dependencies on part of a composite key, and 3NF removes dependencies between non-key columns.
- What is the difference between const and readonly in C#?
A const is a compile-time constant that must be assigned where it is declared, while a readonly field can be assigned at declaration or in the constructor, so its value can be decided at runtime.
- What is the difference between ref and out parameters in C#?
Both pass an argument by reference, but ref requires the variable to be initialised before the call, while out requires the method to assign a value before it returns.
- What is the difference between an abstract class and an interface in C#?
An abstract class can hold state, constructors and partial implementation but a class can inherit only one, while an interface defines a contract that a class can implement many of.
- What is boxing and unboxing in C# and why does it affect performance?
Boxing converts a value type to object by allocating it on the heap, and unboxing converts it back; both add allocations and casts, so avoid them in hot code paths.
- What is LINQ in C# and what is deferred execution?
LINQ (Language Integrated Query) lets you query collections, databases and XML with a consistent syntax, and deferred execution means a query does not run when you define it but when you enumerate the results.
- What is the difference between an abstract class and an interface in Java?
An abstract class can have instance fields, constructors and a mix of implemented and abstract methods but supports only single inheritance, while an interface defines a contract that a class can implement multiple times and, since Java 8, can include default methods.
- What is the difference between ArrayList and LinkedList in Java?
ArrayList is backed by a resizable array with O(1) index access and O(n) insertion in the middle, while LinkedList is a doubly linked list with O(n) index access and O(1) insertion once you hold the node; in practice ArrayList is faster for most workloads.
- What is the difference between checked and unchecked exceptions in Java?
Checked exceptions (subclasses of Exception other than RuntimeException) must be caught or declared with throws, while unchecked exceptions (RuntimeException and Error) do not have to be handled and usually signal programming bugs.
- What are the main features of Java 8: lambdas, streams and Optional?
Java 8 introduced lambda expressions, functional interfaces, the Stream API for declarative collection processing, Optional to represent missing values, default methods in interfaces, method references and the java.time date and time API.
- What are *args and **kwargs in Python?
*args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary, which lets a function accept a variable number of arguments.
- Why should you not use a mutable default argument in Python?
Default argument values are evaluated once when the function is defined, so a default list or dictionary is shared between every call that does not pass its own, causing data to leak between calls.
- What is the difference between a shallow copy and a deep copy in Python?
A shallow copy creates a new container but reuses the same nested objects, while a deep copy recursively copies everything so the new object is fully independent.
- What is the difference between @staticmethod and @classmethod in Python?
A classmethod receives the class as its first argument (cls) and can create or configure instances, while a staticmethod receives no automatic argument and is just a function placed inside the class namespace.
- What is the difference between require and import in Node.js?
require is the CommonJS module system, which loads modules synchronously at runtime, while import is the ES module standard, which is statically analysed, asynchronous and supports top-level await and tree shaking.
- What is middleware in Express and how does it work?
Middleware are functions that receive the request, response and a next callback; they run in the order they are registered and can modify the request, end the response or pass control on with next().
- What is the difference between horizontal and vertical scaling?
Vertical scaling means giving one machine more CPU, memory or disk, while horizontal scaling means adding more machines and spreading the load across them.
- What is a load balancer and what are the common load balancing algorithms?
A load balancer distributes incoming requests across several servers to improve capacity and availability, using algorithms such as round robin, least connections or consistent hashing.
Mid-level (2-5 years)
- What is type narrowing in TypeScript?
Narrowing is when TypeScript shrinks a wide type (such as a union) to a more specific type after a runtime check like typeof, instanceof, in, or a custom type guard.
- What is the difference between enum and union types in TypeScript?
A string union such as "admin" | "user" exists only in the type system and erases to plain strings. A TypeScript enum compiles to a JavaScript object (unless it is a const enum), which is extra runtime code and a weaker default.
- How does TypeScript type inference work?
TypeScript fills in types you omit: literals get their literal or widened type, function return types are inferred from return statements, and generic arguments are inferred from the values you pass.
- What are ACID properties in a database?
ACID stands for Atomicity, Consistency, Isolation and Durability: a transaction either fully succeeds or fully fails, keeps the data valid, does not interfere with other transactions, and survives crashes once committed.
- What is an index in SQL and how does it improve performance?
An index is a separate sorted data structure (usually a B-tree) that lets the database find rows without scanning the whole table, at the cost of extra storage and slower writes.
- What is the difference between a clustered and a non-clustered index?
A clustered index defines the physical order in which the table's rows are stored, so there can be only one per table, while a non-clustered index is a separate structure that points back to the rows.
- What is the difference between IEnumerable and IQueryable in C#?
IEnumerable runs the query in memory using delegates, while IQueryable builds an expression tree that a provider such as Entity Framework translates into SQL, so filtering happens in the database.
- What are transient, scoped and singleton service lifetimes in ASP.NET Core dependency injection?
Transient services are created every time they are requested, scoped services are created once per HTTP request, and singleton services are created once and shared for the life of the application.
- What is the difference between Task and Thread, and how does async/await work in C#?
A Thread is an operating-system execution unit, while a Task represents an asynchronous operation scheduled on the thread pool; await releases the current thread while the operation is pending and resumes the method when it completes.
- How does garbage collection work in C# and when should you use IDisposable?
The .NET garbage collector automatically frees managed objects that are no longer reachable, organising them into generations 0, 1 and 2 so short-lived objects are collected cheaply, and IDisposable is used to release unmanaged resources such as files and connections promptly.
- How does HashMap work internally in Java?
A HashMap stores entries in an array of buckets; it computes the key's hash code to choose a bucket, resolves collisions with a linked list that becomes a red-black tree when a bucket grows large, and resizes when the load factor of 0.75 is exceeded.
- What is the difference between HashMap, Hashtable and ConcurrentHashMap in Java?
HashMap is not thread-safe, Hashtable is thread-safe by locking the whole map on every method, and ConcurrentHashMap is thread-safe with much finer-grained locking and lock-free reads, so it scales far better.
- How does JVM memory management and garbage collection work in Java?
The JVM divides memory into a per-thread stack, a shared heap (split into young and old generations) and Metaspace; the garbage collector frees heap objects that are no longer reachable, collecting short-lived young objects frequently and old objects less often.
- What are decorators in Python and how do they work?
A decorator is a function that takes another function and returns a modified version of it, letting you add behaviour such as logging, caching or access control without changing the original code.
- What are generators and the yield keyword in Python?
A generator is a function that uses yield to produce values one at a time and remembers its state between calls, so it can process large or infinite sequences without holding everything in memory.
- How does Python manage memory and garbage collection?
CPython frees objects mainly through reference counting, deleting an object as soon as nothing refers to it, and uses a cyclic garbage collector to clean up groups of objects that reference each other.
- What is the difference between process.nextTick, setImmediate and setTimeout in Node.js?
process.nextTick runs its callback right after the current operation, before the event loop continues; setTimeout runs in the timers phase after a minimum delay; and setImmediate runs in the check phase right after the poll (I/O) phase.
- What are streams in Node.js and why should you use them?
Streams process data piece by piece as it arrives instead of loading it all into memory, which lets you handle large files and network data efficiently; they come in Readable, Writable, Duplex and Transform types.
- What is the difference between JWT and session-based authentication?
Session authentication stores the login state on the server and gives the browser a session ID cookie, while JWT authentication gives the client a signed token that contains the user's claims so the server can verify it without storing state.
- How do you secure a Node.js Express API?
Validate all input, use parameterised queries, add security headers with helmet, rate-limit requests, restrict CORS, hash passwords, keep secrets in environment variables, and keep dependencies updated and audited.
- When should you use a SQL database vs a NoSQL database?
Choose SQL when your data is relational and you need transactions, joins and strong consistency; choose NoSQL when you need flexible schemas, very high write throughput or horizontal scaling for a specific access pattern.
- What is caching and what are the common cache invalidation strategies?
Caching stores frequently read data in fast storage such as memory to reduce latency and database load; the main strategies are cache-aside, write-through, write-back and time-based expiry (TTL).
- What is the difference between REST, GraphQL and gRPC?
REST exposes resources over HTTP URLs and is simple and cache-friendly, GraphQL lets clients ask for exactly the fields they need from a single endpoint, and gRPC uses binary Protocol Buffers over HTTP/2 for fast service-to-service calls.
- What is idempotency in REST APIs and why does it matter?
An operation is idempotent if repeating it any number of times has the same effect as doing it once; it matters because network retries can otherwise create duplicate orders or payments.
- How do you design a rate limiter?
Choose an algorithm such as token bucket or sliding window, store a counter per client (by user ID, API key or IP) in a fast shared store like Redis, and return HTTP 429 with a Retry-After header when the limit is exceeded.
Senior (5+ years)
- What are mapped types and conditional types in TypeScript?
Mapped types build a new object type by looping over keys (`{ [K in keyof T]: ... }`). Conditional types pick a result with `T extends U ? X : Y`, which is how many utility types are implemented.
- What are transaction isolation levels in SQL and what problems do they prevent?
Isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) control how much concurrent transactions can see of each other's changes, trading consistency against concurrency to prevent dirty reads, non-repeatable reads and phantom reads.
- How do you optimize a slow SQL query?
Read the execution plan with EXPLAIN to find full scans and expensive joins, add or fix indexes for the filter and join columns, select only the columns and rows you need, and rewrite predicates so indexes can be used.
- How do you avoid deadlocks with async/await in C#?
Use async all the way down instead of blocking on tasks with .Result or .Wait(), and in library code use ConfigureAwait(false) so continuations do not need to return to a captured context.
- What is the difference between synchronized and volatile in Java, and how do you avoid deadlocks?
synchronized gives mutual exclusion and memory visibility for a block of code, while volatile only guarantees that reads and writes of one variable are visible to all threads and does not make compound operations such as count++ atomic.
- What is the GIL in Python and how does it affect multithreading?
The Global Interpreter Lock (GIL) in CPython lets only one thread execute Python bytecode at a time, so threads do not speed up CPU-bound code but still help with I/O-bound work.
- What is the difference between threading, multiprocessing and asyncio in Python?
Threading runs concurrent threads that share memory and suit blocking I/O, multiprocessing runs separate processes to use multiple CPU cores for CPU-bound work, and asyncio runs many non-blocking tasks cooperatively on one thread for high-volume I/O.
- How do you scale a Node.js application and avoid blocking the event loop?
Keep the main thread free by moving CPU-heavy work to worker threads or a job queue, and scale across cores and machines by running multiple processes (cluster or PM2) behind a load balancer with shared, external state.
- How do you design a URL shortener like bit.ly?
Generate a short unique code for each long URL (for example by base62-encoding a unique ID), store the mapping in a key-value or relational database, serve redirects through a cache because reads far outnumber writes, and record analytics asynchronously.
- What is the CAP theorem and what does it mean in practice?
The CAP theorem says that during a network partition a distributed system must choose between consistency (every read sees the latest write) and availability (every request gets a response); you cannot have both while the partition lasts.
- What is the difference between database sharding and replication?
Replication copies the same data to several servers to improve read capacity and availability, while sharding splits the data across servers so each holds only a part, which increases write capacity and total storage.
- Monolith vs microservices: which should you choose?
Start with a well-structured monolith unless you have several teams and clear service boundaries, because microservices add distributed-system complexity such as network failures, data consistency and operational overhead.