Beginner Level (0–1 Years)

1. What is the output of the following code?
console.log(typeof null);

Answer:

The output is "object". This is a well-known JavaScript quirk due to legacy implementation behavior. Although null is a primitive, typeof null returns “object”.

2. How does a compiled language differ from an interpreted one?

Answer:

A compiled language is transformed into machine code before runtime, often resulting in faster execution (e.g., C++). An interpreted language executes instructions line-by-line at runtime (e.g., Python). However, many modern languages like Java and JavaScript use hybrid models (e.g., JIT compilation), making this distinction less clear-cut.

3. In Python, what’s the difference between is and ==?

Answer:

== checks for value equality, while is checks for identity (whether two variables point to the same object in memory). For example, [1, 2] == [1, 2] is True, but [1, 2] is [1, 2] is False because they are different objects. Note: Python interns small integers (-5 to 256), so 1000 is 1000 may be True in some cases.

4. What does the following SQL return?
SELECT NULL = NULL;

Answer:

In standard SQL, it returns NULL. NULL represents an unknown value, so any comparison like NULL = NULL yields NULL. Use IS NULL or IS NOT NULL for proper comparisons.

5. What is the difference between stack and heap memory?

Answer:

The stack is used for static memory allocation (local variables, function calls), while the heap is for dynamic memory (objects, arrays). Stack is faster but limited in size. Heap can cause fragmentation and requires manual or automatic memory management.

6. What will this Java code print?
System.out.println(10 + 20 + "30");

Answer:

It prints 3030. The integers are added first (10 + 20 = 30), then concatenated with the string “30”.

7. Can you override a static method in Java?

Answer:

No. Static methods are bound to the class, not instances, so they cannot be overridden. They can be hidden if redefined in a subclass.

8. What are some common steps to debug a program that’s not working as expected?

Answer:

First, reproduce the issue to understand its context. Check error messages or logs for clues. Use print statements or a debugger to trace variable values and program flow. Verify inputs and assumptions, and test small code sections to isolate the problem. Finally, research the issue online or in documentation if needed.

9. What is a race condition?

Answer:

A race condition occurs when the timing of threads or processes causes unexpected behavior due to shared resource access. It’s common in multithreaded environments when proper synchronization is missing.

10. What is the time complexity of accessing an element in a Python list?

Answer:

Accessing an element by index has a time complexity of O(1). However, operations like in (e.g., x in list) are O(n).

11. Why is floating-point arithmetic often inaccurate?

Answer:

Because binary cannot exactly represent most decimal fractions. This leads to rounding errors, e.g., 0.1 + 0.2 != 0.3.

12. Can a function return multiple values in JavaScript?

Answer:

Yes, by returning an array or object, which can be destructured. Example: function getValues() { return [1, 2]; } const [a, b] = getValues(); assigns 1 to a and 2 to b.

13. Is HTML a programming language?

Answer:

No. HTML is a markup language used for structuring content. It lacks logic or flow control features of programming languages.

14. In CSS, what is the specificity of #id .class p?

Answer:

The specificity is 1,1,1: one ID, one class, one element.

15. What is a REST API, and what is an example of an HTTP method used in it?

Answer:

A REST API (Representational State Transfer) is a way for systems to communicate over the web using HTTP. It uses standard HTTP methods to perform actions on resources, like retrieving or updating data. An example is the GET method, used to fetch data from a server, such as retrieving a user’s profile from /api/users/123.

16. What is the difference between let and var in JavaScript?

Answer:

let is block-scoped and not hoisted in the same way as var. var is function-scoped and hoisted to the top of its scope.

17. What does it mean when a language is “dynamically typed”?

Answer:

It means that variable types are determined at runtime, not in advance. This allows for more flexibility but can cause runtime errors if not handled properly.

18. In Git, what’s the difference between git fetch and git pull?

Answer:

git fetch updates your remote tracking branches but does not merge, while git pull fetches and then merges into your current branch.

19. What is a memory leak?

Answer:

A memory leak occurs when a program fails to release memory that’s no longer needed, leading to decreased performance and possible crashes over time.

20. What is a Git branch, and why is it useful?

Answer:

A Git branch is a separate line of development in a repository, allowing you to work on features or fixes without affecting the main codebase. For example, you can create a branch called feature-login to build a new login feature. It’s useful for collaboration, testing changes, and keeping the main branch stable.

21. What will be the output of this Python snippet?
print("5" * 3)

Answer:

It prints "555". Python repeats the string, not multiplies numerically.

22. What is the difference between = and == in most languages?

Answer:

= is the assignment operator; == is the equality comparison operator. Confusing them can lead to logical errors or syntax errors.

23. How does JavaScript handle asynchronous code execution?

Answer:

Via the event loop. JavaScript uses the call stack, web APIs, and the task queue to manage asynchronous tasks like setTimeout or fetch.

24. What will this JavaScript expression evaluate to?
[] + []

Answer:

It evaluates to "" (an empty string). Adding two arrays triggers coercion to strings.

25. Why is it bad to catch general exceptions in most languages?

Answer:

Because it may hide real issues like syntax errors, memory problems, or logic bugs. Catching broad exceptions makes debugging and error handling harder and can lead to unpredictable behavior.


👋 Need top software developers for your project? Interview this week!

Fill out the form to book a call with our team. We’ll match you to the top developers who meet your requirements, and you’ll be interviewing this week!

Request for Service


Intermediate Level (1–3 Years)

1. What is the difference between shallow copy and deep copy in JavaScript?

Answer:

A shallow copy duplicates only the top-level properties, while a deep copy recursively copies all nested objects. For example, Object.assign({}, obj) creates a shallow copy, while JSON.parse(JSON.stringify(obj)) creates a deep copy (with limitations like not handling functions or circular references).

2. Why might a floating-point sum like 0.1 + 0.2 not equal 0.3?

Answer:

Because of binary floating-point representation issues. The values cannot be represented exactly in binary, causing small rounding errors. 0.1 + 0.2 === 0.3 returns false in JavaScript.

3. What is a closure and why is it useful?

Answer:

A closure is a function that retains access to variables from its outer scope even after the outer function has finished executing. This is useful for data encapsulation and creating factory functions, e.g., function makeCounter() { let count = 0; return () => count++; }.

4. In Python, what does mutable default argument mean and why is it dangerous?

Answer:

Default arguments are evaluated once at function definition. If mutable (e.g., a list), the same object is shared across calls. Example: def f(x=[]): x.append(1); return x prints [1], then [1, 1] on subsequent calls. Fix: def f(x=None): x = x or []; x.append(1); return x.

5. Explain what a race condition is in a multithreaded environment.

Answer:

A race condition occurs when the system’s outcome depends on the non-deterministic order of thread execution, often due to unsynchronized access to shared resources. It can cause bugs like incorrect data updates.

6. What is the difference between composition and inheritance?

Answer:

Inheritance defines an “is-a” relationship, while composition defines a “has-a” relationship. Composition is generally preferred for flexibility and testability, as it avoids tight coupling and allows dynamic behavior.

7. What will the following JavaScript return?
typeof NaN

Answer:

It returns "number". NaN stands for “Not a Number” but is still of type number in JavaScript.

8. Why might using eval() be dangerous?

Answer:

It executes arbitrary code, which can lead to security vulnerabilities, especially if user-controlled input is evaluated. It also breaks optimization in JavaScript engines, reducing performance.

9. What is the output of this Python code?
a = [1, 2, 3]
b = a
a.append(4)
print(b)

Answer:

The output is [1, 2, 3, 4] because a and b reference the same list in memory.

10. In SQL, what does the HAVING clause do that WHERE cannot?

Answer:

HAVING filters aggregate results after grouping, whereas WHERE filters rows before grouping. Example: SELECT dept, COUNT(*) FROM employees GROUP BY dept HAVING COUNT(*) > 5;.

11. What is the difference between synchronous and asynchronous programming?

Answer:

Synchronous code executes line by line, blocking further execution until the current task completes. Asynchronous code allows tasks to run concurrently, using callbacks, promises, or async/await to avoid blocking.

12. What does the following return in JavaScript?
[1, 2, 3].map(parseInt)

Answer:

It returns [1, NaN, NaN]. map passes (element, index, array) to parseInt, which expects (string, radix). parseInt("2", 1) and parseInt("3", 2) use invalid radices, returning NaN.

13. What is the significance of HTTP status code 204?

Answer:

It means “No Content”. The server successfully processed the request, but there is no content to send back. Commonly used in DELETE operations or updates that require no response body.

14. What’s the difference between const and Object.freeze()?

Answer:

const prevents reassignment of the variable binding, but the object it points to can still be modified. Object.freeze() makes the object immutable (shallowly).

15. In Python, what is a generator and how is it different from a list?

Answer:

A generator produces items on-the-fly using yield, saving memory. Lists store all elements in memory. Generators are more memory-efficient for large data or streams, e.g., def gen(): for i in range(3): yield i.

16. How does garbage collection work in Java?

Answer:

Java uses automatic garbage collection. The JVM identifies unreachable objects (no references) and reclaims their memory using algorithms like generational GC, mark-and-sweep, or G1 GC, depending on the JVM version.

17. What is “callback hell” and how can it be avoided?

Answer:

“Callback hell” refers to deeply nested callbacks that make code hard to read and maintain. It can be avoided using Promises or async/await for cleaner asynchronous code flow.

18. What’s the difference between == and === in JavaScript?

Answer:

== performs type coercion before comparison, while === checks both value and type. For example, 0 == "0" is true, but 0 === "0" is false.

19. What is a promise in JavaScript?

Answer:

A Promise represents a value that may be available now, in the future, or never. It has three states: pending, fulfilled, and rejected. It’s used for asynchronous operations, e.g., fetch.

20. What’s the difference between TCP and UDP?

Answer:

TCP is connection-oriented, reliable, and ensures ordered delivery. UDP is connectionless, faster, but does not guarantee delivery or order. Use TCP for web traffic, UDP for streaming or gaming.

21. What is the difference between an abstract class and an interface in Java?

Answer:

An abstract class can have implemented methods and state, while an interface (pre-Java 8) can only have method signatures. Since Java 8, interfaces can have default/static methods. A class can implement multiple interfaces but extend only one abstract class.

22. What is event bubbling in the DOM?

Answer:

Event bubbling is when an event triggered on a child element propagates up to its ancestors. For example, clicking a button inside a div triggers the button’s handler, then the div’s, unless event.stopPropagation() is called.

23. How does SQL injection work and how can it be prevented?

Answer:

SQL injection occurs when user input is concatenated into SQL queries, allowing attackers to modify queries (e.g., SELECT * FROM users WHERE id = '1; DROP TABLE users;'). Prevent using parameterized queries or ORM frameworks to safely escape inputs.

24. What’s the difference between Array.map() and Array.forEach()?

Answer:

map() returns a new array with transformed items. forEach() iterates and executes a function but returns undefined. Use map() for transformations, forEach() for side effects.

25. In Git, what is the difference between rebase and merge?

Answer:

merge combines two branches and creates a new commit. rebase moves a branch to start from a new base commit, rewriting history. rebase keeps history linear but should be avoided on shared branches.

26. What is the use of a virtual DOM?

Answer:

Virtual DOM is a lightweight in-memory representation of the real DOM. Libraries like React use it to optimize rendering by updating only the parts of the DOM that changed, improving performance.

27. What is tail-call optimization and does JavaScript support it?

Answer:

Tail-call optimization (TCO) reuses the current stack frame for tail-recursive calls, preventing stack overflows. ES6 introduced TCO in strict mode, and modern engines (e.g., V8, Safari) support it, though not universally. Use with caution in cross-environment code.

28. What is unit testing, and why is it important in software development?

Answer:

Unit testing involves testing individual components (e.g., functions or methods) in isolation to ensure they work as expected. It’s important for catching bugs early, verifying code behavior, and enabling safe refactoring. Frameworks like Jest (JavaScript) or pytest (Python) are commonly used.

29. How do you detect memory leaks in a web application?

Answer:

Use Chrome DevTools’ Memory tab to identify detached DOM nodes or monitor memory usage over time. Common leaks include forgotten timers, event listeners, or closures retaining references. Use WeakMap or ensure cleanup to prevent leaks.

30. In JavaScript, what does Function.prototype.bind() do?

Answer:

It creates a new function with a bound this context and optionally preset arguments. Useful when passing object methods as callbacks, e.g., obj.method.bind(obj) ensures this refers to obj.

31. What is the difference between REST and GraphQL?

Answer:

REST exposes multiple endpoints with fixed responses. GraphQL uses a single endpoint where clients specify exactly what data they need, reducing over-fetching or under-fetching. GraphQL adds server-side complexity but improves client flexibility.

32. What will this code print and why?
let a = (1, 2, 3); console.log(a);

Answer:

It prints 3. The comma operator evaluates all expressions and returns the last one, so (1, 2, 3) evaluates to 3.

33. What’s the difference between localStorage and sessionStorage?

Answer:

localStorage persists data until explicitly cleared. sessionStorage is cleared when the page session ends (e.g., tab or window closed). Both store data as strings in key/value pairs.

34. What is hoisting in JavaScript?

Answer:

Hoisting moves variable and function declarations to the top of their scope during compilation. Only declarations are hoisted, not initializations. let and const are hoisted but remain in a temporal dead zone until defined.

35. Why is setTimeout(fn, 0) not truly immediate?

Answer:

It places fn at the end of the event queue. The function runs only after the current call stack is cleared, so it’s delayed slightly even with a 0 ms delay.

36. How would you use a regular expression to validate an email address?

Answer:

A regular expression for basic email validation might be /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/. It checks for a local part, an @ symbol, a domain, and a top-level domain. Example in JavaScript: const isValid = email.match(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/);. Use libraries for production to handle edge cases.

37. What is the difference between throw and return in error handling?

Answer:

throw stops execution and propagates an error to be caught by a try-catch block. return passes control back to the caller with a value. Use throw for unexpected conditions, return for expected outcomes.

38. In React, what is the purpose of a key in a list?

Answer:

Keys help React identify which items have changed, are added, or removed in a list. They improve rendering efficiency and must be unique and stable across renders (avoid using indexes if the list order changes).

39. What are the main differences between GET and POST HTTP methods?

Answer:

GET retrieves data, appends parameters to the URL, and is idempotent. POST sends data in the request body, is used to create/update resources, and is not idempotent.

40. What is the difference between splice() and slice() in JavaScript?

Answer:

splice() modifies the original array by removing or replacing elements. slice() returns a shallow copy of a portion without modifying the original.

41. What is the difference between pass-by-value and pass-by-reference?

Answer:

In pass-by-value, a copy of the variable is passed (e.g., primitives in JavaScript). In pass-by-reference, the reference to the original object is passed (e.g., objects/arrays in JavaScript). Changes to referenced objects affect the original.

42. What will this code print?
console.log(1 && 2 || 3 && 4);

Answer:

It prints 2. 1 && 2 evaluates to 2, then 2 || 4 evaluates to 2. Logical operators return the last evaluated operand, not just true/false.

43. What is the difference between authentication and authorization?

Answer:

Authentication verifies identity (e.g., login with username/password). Authorization determines what an authenticated user can access (e.g., permissions or roles). They are separate security steps.

44. What is a memory leak and how do you prevent it in JavaScript?

Answer:

A memory leak occurs when memory is no longer needed but not released, e.g., due to closures, forgotten timers, or detached DOM nodes. Prevent with proper cleanup (e.g., remove event listeners) or use WeakMap for weak references.

45. What are higher-order functions in JavaScript?

Answer:

Functions that take other functions as arguments or return them. Examples include map(), filter(), and reduce(). They enable functional programming patterns like composition and abstraction.

46. How do web servers handle multiple client requests simultaneously?

Answer:

Through concurrency models: threads, processes, or async event loops. For example, Node.js uses a single-threaded event loop; Apache uses multi-threading or forking depending on configuration.

47. What’s the difference between a process and a thread?

Answer:

A process has its own memory and resources. A thread is a lightweight execution unit within a process, sharing the process’s memory. Threads are faster to create but risk race conditions due to shared memory.

48. What is dependency injection and why is it useful?

Answer:

Dependency injection provides dependencies from outside a class/module instead of creating them inside. It improves modularity, testability, and reduces tight coupling, e.g., passing a database connection to a service.

49. What’s the difference between null and undefined in JavaScript?

Answer:

undefined means a variable is declared but not assigned. null is a primitive value representing intentional absence of value. Despite typeof null returning "object", null is not an object.

50. What is the time complexity of a binary search, and why is it efficient?

Answer:

Binary search has a time complexity of O(log n). It works by repeatedly dividing a sorted array in half, making it efficient for large datasets compared to linear search (O(n)). It requires the input to be sorted.


LATAM-Image-V2.png

Hire Top LATAM Developers: Guide

We’ve prepared this guide that covers  benefits, costs, recruitment, and remote team management to a succesful hiring of developers in LATAM. 

Fill out the form to get our guide.

Gated content


Advanced Level (3+ Years)

1. What is the CAP Theorem and how does it apply to distributed systems?

Answer:

CAP Theorem states that a distributed system can only guarantee two of Consistency, Availability, and Partition Tolerance at a time. Since network partitions are inevitable, systems choose between Consistency (e.g., CP systems like ZooKeeper) or Availability (e.g., AP systems like Cassandra) during partitions.

2. Explain the difference between optimistic and pessimistic locking in databases.

Answer:

Optimistic locking assumes conflicts are rare and checks for conflicts before committing changes (e.g., using version numbers). Pessimistic locking locks the resource early to prevent conflicts. Optimistic is preferred for high concurrency; pessimistic for high contention.

3. What’s the difference between monolithic, microservices, and serverless architectures?

Answer:

Monolithic: single codebase, tightly coupled components. Microservices: independent, loosely coupled services. Serverless: functions triggered by events, with automatic scaling and no server management.

4. How does the JVM manage memory and what are the GC generations?

Answer:

The JVM uses heap memory divided into Young (Eden, Survivor) and Old generations. Objects start in Young Gen and are promoted to Old Gen. Garbage Collection uses collectors like G1 (default in modern Java), ZGC, or Shenandoah for low-pause collection. CMS is deprecated since Java 14.

5. What are the key differences between threads and coroutines?

Answer:

Threads are OS-managed, heavyweight, and consume more memory. Coroutines are lightweight, cooperative multitasking units managed by the language runtime (e.g., Kotlin, Python), offering better scalability for async tasks.

6. What does ACID stand for in databases?

Answer:

Atomicity, Consistency, Isolation, Durability. These ensure reliable transactions: all-or-nothing execution, valid state transitions, no dirty reads, and persistence despite crashes.

7. Describe a situation where eventual consistency is acceptable.

Answer:

Eventual consistency is suitable for systems like social media feeds or analytics dashboards, where slight delays in data propagation are tolerable, and availability is prioritized over strict consistency.

8. What is false sharing in multithreaded programming?

Answer:

False sharing occurs when threads modify variables on the same CPU cache line, causing unnecessary cache invalidation and performance degradation. Padding variables or using cache line-aware structures can mitigate it.

9. How do you prevent SQL injection in dynamically built queries?

Answer:

Use parameterized or prepared statements, avoid string concatenation of user inputs, apply input validation, and use ORM frameworks that escape inputs by default.

10. What is a memory barrier and why is it important?

Answer:

A memory barrier enforces an ordering constraint on memory operations. It ensures proper visibility and consistency in multithreaded environments, especially with modern CPUs that reorder instructions for performance.

11. What is the difference between horizontal and vertical scaling?

Answer:

Vertical scaling adds more resources (CPU, RAM) to a single machine. Horizontal scaling adds more machines to distribute the load. Horizontal scaling is more fault-tolerant and suited for cloud-native systems.

12. Explain how a hash table handles collisions.

Answer:

Collisions are handled via chaining (linked lists at buckets) or open addressing (probing for next available slot). Good hash functions and load factor management reduce collisions.

13. How does the actor model differ from thread-based concurrency?

Answer:

In the actor model (e.g., Akka, Erlang), actors are isolated units that communicate via message passing, avoiding shared memory. Threads often share memory and require locks, increasing complexity.

14. What’s the difference between a soft link and a hard link in Unix?

Answer:

A hard link points directly to the inode of a file, indistinguishable from the original. A soft (symbolic) link points to the file path. If the original file is deleted, soft links break; hard links don’t.

15. Explain how garbage collection works in Go.

Answer:

Go uses a concurrent, non-generational mark-and-sweep garbage collector with tricolor marking (white, grey, black) and write barriers. It runs concurrently with application code, minimizing pauses, and optimizes for short-lived objects.

16. What is dependency injection and how does it relate to the SOLID principles?

Answer:

Dependency injection provides objects with their dependencies rather than letting them construct them. It supports the Dependency Inversion Principle, improving modularity, testability, and flexibility.

17. What are idempotent operations and why are they important in APIs?

Answer:

Idempotent operations produce the same result regardless of how many times they’re applied. PUT and DELETE should be idempotent to prevent issues in retry logic or network failures.

18. Describe how TLS handshake works.

Answer:

The client and server exchange cryptographic keys via: client hello, server certificate, key exchange, and encryption setup. It establishes a secure channel using asymmetric encryption, then switches to symmetric encryption for performance.

19. What are some disadvantages of microservices?

Answer:

Increased complexity, network overhead, distributed data management, harder debugging and testing, and greater DevOps burden (deployment, monitoring, observability).

20. How do you debug a memory leak in a long-running backend service?

Answer:

Use profiling tools (e.g., Valgrind, VisualVM, pprof). Track heap usage, identify retained objects, monitor open file descriptors/sockets, and analyze GC logs to find objects that shouldn’t persist.

21. What is CQRS and when would you use it?

Answer:

CQRS (Command Query Responsibility Segregation) separates read and write models. It’s useful in systems with different performance or consistency needs for reads vs. writes, especially with event sourcing or high-throughput domains.

22. What are strong, weak, and soft references in Java?

Answer:

Strong references prevent GC. Soft references are cleared when memory is low. Weak references are cleared at the next GC. Useful for caching or memory-sensitive objects.

23. How do you handle eventual consistency in a distributed system, and what impact does it have on user experience?

Answer:

Handle eventual consistency with conflict resolution (e.g., CRDTs, vector clocks), retries, idempotent operations, and versioning. Users may see stale data, mitigated by showing timestamps, client-side reconciliation, or stronger consistency for critical paths.

24. What is the difference between a semaphore and a mutex?

Answer:

A mutex allows one thread access at a time. A semaphore can allow a fixed number of threads access. Mutex is binary; semaphores can be counting. Semaphores are better for resource pools; mutexes for critical sections.

25. How do you prevent cascading failures in microservices?

Answer:

Use circuit breakers, bulkheads, retries with backoff, timeouts, and failover strategies. Monitor service health and isolate failures to avoid full-system outages.

26. What is cache invalidation and why is it hard?

Answer:

Cache invalidation removes outdated data from the cache. It’s hard due to timing, concurrency, stale reads, and ensuring consistency between cache and source data.

27. What’s the difference between a monorepo and polyrepo?

Answer:

Monorepo contains multiple projects in a single repo, enabling easier dependency sharing and consistency. Polyrepo splits projects into separate repos, promoting isolation and decentralized ownership.

28. How does a blockchain maintain immutability?

Answer:

Each block includes a hash of the previous block. Modifying any block breaks the chain unless all subsequent blocks are recalculated, which is computationally infeasible in decentralized networks with consensus rules.

29. What is backpressure in reactive programming?

Answer:

Backpressure controls flow when producers emit data faster than consumers can handle. It prevents memory overflows using buffering, dropping, or throttling strategies.

30. What are the advantages and risks of using reflection?

Answer:

Reflection allows inspection and dynamic invocation of code at runtime. Useful for frameworks and dynamic behaviors, but it can break encapsulation, reduce performance, and complicate security and debugging.

31. What is a bloom filter and where would you use it?

Answer:

A bloom filter is a space-efficient probabilistic data structure for testing membership. It can return false positives but never false negatives. Useful in caching, databases, and duplicate detection where memory is constrained.

32. Explain the role of quorum in distributed databases.

Answer:

Quorum ensures consistency by requiring a minimum number of nodes to agree on a value before proceeding. It’s used in replication and consensus protocols (e.g., Cassandra, Raft) to balance consistency and availability.

33. What is a distributed consensus algorithm, and how does Raft differ from Paxos?

Answer:

A distributed consensus algorithm ensures agreement among nodes in a distributed system despite failures. Raft simplifies Paxos by breaking consensus into leader election, log replication, and safety, making it easier to understand and implement. Paxos is more general but complex, with multiple roles (proposer, acceptor, learner).

34. What is the difference between latency and throughput?

Answer:

Latency is the time to process a single request. Throughput is the number of requests handled in a given time. Low latency doesn’t always mean high throughput and vice versa.

35. What are the benefits and challenges of event sourcing?

Answer:

Event sourcing stores changes as a sequence of events. Benefits: audit trails, flexibility, scalability. Challenges: complexity, event versioning, and rebuilding state efficiently.

36. How does Kubernetes handle rolling updates?

Answer:

Kubernetes updates pods gradually, creating new ones and terminating old ones according to the update strategy. It ensures availability using readiness probes and controls surge/maximum unavailable pods.

37. What is a red-black tree and why is it useful?

Answer:

A red-black tree is a self-balancing binary search tree with O(log n) time for insertion, deletion, and lookup. It maintains balance through color rules and rotations, ideal for map/set implementations.

38. How do you scale a database for write-heavy workloads?

Answer:

Options include sharding, partitioning, write-behind caching, using message queues for buffering, and choosing databases optimized for write throughput (e.g., Cassandra, InfluxDB).

39. What are some common anti-patterns in microservices?

Answer:

Examples: shared database across services, tight coupling, improper service boundaries, duplicated logic, and poor observability. These reduce maintainability and scalability.

40. What are some ways to secure APIs?

Answer:

Use HTTPS, OAuth2/JWT for authentication, rate limiting, IP whitelisting, input validation, CORS headers, and API gateways for centralized control and monitoring.

41. What is a dead letter queue and when should you use it?

Answer:

A dead letter queue (DLQ) stores messages that a queue system fails to process after several attempts. It’s used for debugging, auditing, and preventing infinite retries from clogging up message queues.

42. What is observability in distributed systems, and what are its key components?

Answer:

Observability is the ability to understand a system’s internal state from its external outputs. Key components include logs (events), metrics (numerical data), and traces (request flows across services). Tools like Prometheus, Grafana, and Jaeger enable monitoring and debugging.

43. What is tail latency and why is it important?

Answer:

Tail latency refers to worst-case response times (e.g., 99th percentile). It’s critical in systems where occasional slow responses hurt performance or user experience (e.g., search, finance, real-time apps).

44. What are some common techniques to ensure backward compatibility in APIs?

Answer:

Use versioning (URI or header-based), never remove fields (deprecate first), make additive changes, tolerate unknown fields, and design contracts using schemas (e.g., OpenAPI).

45. How does a content delivery network (CDN) improve web performance?

Answer:

CDNs cache content at edge locations closer to users, reducing latency, server load, and improving availability. They also offer DDoS protection, TLS offloading, and analytics.

46. What is speculative execution and how did it lead to vulnerabilities like Spectre?

Answer:

Speculative execution allows CPUs to predict and execute instructions for speed. Spectre exploited branch prediction and cache timing attacks to leak protected memory via unsafe speculative paths not properly isolated.

47. How do database indexes impact performance?

Answer:

Indexes speed up reads but slow down writes and increase storage. Choosing the right indexes (composite, partial, covering) and maintaining them is key to query optimization.

48. How does OAuth 2.0 differ from OpenID Connect?

Answer:

OAuth 2.0 is an authorization protocol; OpenID Connect is an identity layer on top of OAuth 2.0. OIDC adds authentication via ID tokens, user info endpoint, and standardized scopes.

49. What’s the difference between a message queue and a stream processing system?

Answer:

Message queues (e.g., RabbitMQ) are point-to-point and often ephemeral. Stream processing systems (e.g., Kafka) store logs durably, support replay, and are optimized for real-time data pipelines and analytics.

50. What are database transaction isolation levels, and how do they impact performance?

Answer:

Isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) define how transactions interact. Higher levels (e.g., Serializable) prevent anomalies like dirty reads but increase locking overhead, reducing concurrency. Lower levels (e.g., Read Committed) improve performance but risk inconsistencies.