OneBase.AI Interview Questions and Technical Assessment Overview
Preparing for a technical interview requires more than understanding programming concepts. Companies also expect candidates to apply their knowledge to real-world problems, write working code, and find solutions when something goes wrong in an application.
The OneBase.AI technical interview questions cover important areas of full-stack development, including React, Spring Boot, PostgreSQL, and application debugging. These questions focus on practical situations that developers may face while building and maintaining software applications.
For example, candidates may be asked to create an employee search screen using React, develop a book borrowing API using Spring Boot, write SQL queries to analyse customer orders, or identify problems that cause duplicate orders and negative stock in an e-commerce application.
These questions help evaluate how well candidates understand the technologies and how they approach programming problems. Instead of simply writing code, candidates should also be able to explain their logic, identify possible issues, and understand why a particular solution works.
In this blog, we will cover the OneBase.AI interview questions and answers across four important technical areas:
- 1. React: Building an employee search screen, managing API responses, handling errors, and avoiding unnecessary API calls.
- 2. Spring Boot: Developing REST APIs, working with Spring Data JPA, and handling exceptions using custom exception classes and @ControllerAdvice.
- 3. PostgreSQL: Writing SQL queries, calculating customer order totals, and finding the highest-spending customers.
- 4. Full Stack Debugging: Preventing duplicate orders, understanding database race conditions, and avoiding negative stock using appropriate solutions.
Whether you are a fresher preparing for your first technical interview or a developer looking to improve your full-stack development knowledge, these questions will help you practise important concepts through practical scenarios.
Let’s start with the React interview questions and understand how to build an employee search screen using React.
React Interview Questions and Answers
- React is widely used to build interactive user interfaces for web applications. During a React technical interview, candidates may be asked to create components, manage data, connect APIs, and handle different application states.
- Understanding React concepts such as useState, useEffect, API integration, and event handling is important for solving practical development problems.
- In the following questions, we will look at an employee search screen where employee details are fetched from an API based on the name entered by the user. This scenario helps explain how React handles user input, API requests, loading states, and errors.
React Employee Search Screen Using useState and useEffect
Interview Question:
You are asked to build an employee search screen using React. The application should fetch employee details from the following API whenever the user enters a name:
GET /api/employees?name=<text>
Write a functional component using useState and useEffect to manage the search input and display the matching employees.
Answer:
To build this screen, we need two important React hooks: useState and useEffect.
- 1. useState: It is used to store and update the search input and employee details.
- 2. useEffect: It is used to perform side effects, such as fetching employee details from an API when the search value changes.
First, create a functional component and use useState to store the employee name entered by the user.
Here is a basic implementation:
import React, { useState, useEffect } from "react";
function EmployeeSearch() {
const [search, setSearch] = useState("");
const [employees, setEmployees] = useState([]);
useEffect(() => {
const fetchEmployees = async () => {
try {
const response = await fetch(
`/api/employees?name=${encodeURIComponent(search)}`
);
if (!response.ok) {
throw new Error("Failed to fetch employees");
}
const data = await response.json();
setEmployees(data);
} catch (error) {
console.error(error);
}
};
fetchEmployees();
}, [search]);
return (
<div>
<h2>Employee Search</h2>
<input
type="text"
placeholder="Enter employee name"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
<ul>
{employees.map((employee) => (
<li key={employee.id}>{employee.name}</li>
))}
</ul>
</div>
);
}
export default EmployeeSearch;
How does this code work?
- 1. The useState hook stores the search text entered by the user.
- 2. When the user types something, the onChange event updates the search value.
- 3. The useEffect hook runs whenever the search value changes.
- 4. The fetch() method sends a GET request to the employee API.
- 5. The API response is converted into JSON format.
- 6. The setEmployees() function updates the employee list displayed on the screen.
This approach allows the employee list to update based on the name entered in the search box.
How to Display Loading and Error Messages in React?
Interview Question:
While fetching employee details from an API, how will you display a loading message? What will you do if the API request fails?
Answer:
When an application fetches data from an API, the request may take some time to complete. During this period, users should know that the application is still processing their request.
Similarly, if the API request fails because of a network issue or server error, the application should display a proper error message instead of leaving the screen empty.
We can handle both situations using useState.
Consider the following updated component:
import React, { useState, useEffect } from "react";
function EmployeeSearch() {
const [search, setSearch] = useState("");
const [employees, setEmployees] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
const fetchEmployees = async () => {
setLoading(true);
setError("");
try {
const response = await fetch(
`/api/employees?name=${encodeURIComponent(search)}`
);
if (!response.ok) {
throw new Error("Failed to fetch employees");
}
const data = await response.json();
setEmployees(data);
} catch (err) {
setError(err.message);
setEmployees([]);
} finally {
setLoading(false);
}
};
fetchEmployees();
}, [search]);
return (
<div>
<h2>Employee Search</h2>
<input
type="text"
placeholder="Enter employee name"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
{loading && <p>Loading...</p>}
{error && <p>{error}</p>}
{!loading && !error && (
<ul>
{employees.map((employee) => (
<li key={employee.id}>{employee.name}</li>
))}
</ul>
)}
</div>
);
}
export default EmployeeSearch;
Explanation:
- loading: Stores whether the API request is currently running. When it is true, the application displays the “Loading…” message.
- 1. error: Stores the error message if the API request fails.
- 2. try: Executes the API request and processes the response.
- 3. catch: Handles errors that occur during the request or response processing.
- 4. finally: Runs after the request completes, whether it succeeds or fails, and resets the loading state.
Using these states makes the application easier to understand and improves the user experience. It also helps prevent users from assuming that the application is not responding when an API request takes time.
Why Should You Avoid API Calls on Every Keystroke?
Interview Question:
In the employee search screen, the API is being called every time the user types a character. What is the problem with this approach, and how would you fix it?
Answer:
When a user types an employee name, React updates the search value. Since the useEffect hook depends on that value, it runs again whenever the value changes.
For example, if a user types the name “Rahul”, the application may send five separate API requests:
- R
- Ra
- Rah
- Rahu
- Rahul
This creates unnecessary API requests, increases server workload, and may affect application performance. It can also cause older responses to arrive after newer ones and display outdated search results.
To solve this problem, we can use a technique called Debouncing.
What is Debouncing?
Debouncing is a technique that delays the execution of a function until the user stops performing an action for a specified period.
For example, instead of sending an API request after every keystroke, we can wait for 500 milliseconds after the user stops typing. Only then will the application send the request.
How to Implement Debouncing in React?
We can use setTimeout() and clearTimeout() inside the useEffect hook to implement debouncing.
import React, { useState, useEffect } from "react";
function EmployeeSearch() {
const [search, setSearch] = useState("");
const [employees, setEmployees] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
const timer = setTimeout(async () => {
setLoading(true);
setError("");
try {
const response = await fetch(
`/api/employees?name=${encodeURIComponent(search)}`
);
if (!response.ok) {
throw new Error("Failed to fetch employees");
}
const data = await response.json();
setEmployees(data);
} catch (err) {
setError(err.message);
setEmployees([]);
} finally {
setLoading(false);
}
}, 500);
return () => clearTimeout(timer);
}, [search]);
return (
<div>
<h2>Employee Search</h2>
<input
type="text"
placeholder="Enter employee name"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
{loading && <p>Loading...</p>}
{error && <p>{error}</p>}
{!loading && !error && (
<ul>
{employees.map((employee) => (
<li key={employee.id}>{employee.name}</li>
))}
</ul>
)}
</div>
);
}
export default EmployeeSearch;
How does debouncing work in this code?
- 1. When the user enters a character, the useEffect hook runs.
- 2. The setTimeout() function waits for 500 milliseconds before sending the API request.
- 3. If the user types another character before the timer completes, the cleanup function calls clearTimeout() and cancels the previous timer.
- 4. A new timer starts for the updated search value.
- 5. When the user stops typing for 500 milliseconds, the API request is sent.
This reduces unnecessary API calls and helps improve the performance of the employee search screen.
Important interview point: Debouncing controls when an API request starts, but it does not cancel a request that has already started. In applications where older responses could overwrite newer results, you can also use AbortController to cancel outdated requests.
Understanding useState, useEffect, API integration, loading and error handling, and debouncing will help you solve similar React development problems in technical interviews.
Spring Boot Interview Questions and Answers
Spring Boot is widely used to develop REST APIs and backend applications using Java. During a Spring Boot technical interview, candidates may be asked to create APIs, connect applications with databases, manage business logic, and handle different types of errors.
Understanding concepts such as Spring Data JPA, REST controllers, service classes, dependency injection, and exception handling is important for solving these practical problems.
In this section, we will work with a library book borrowing application. The scenario involves creating a Book entity, developing a REST API to borrow books, reducing the available book count, and handling errors when a book does not exist or no copies are available.
How to Build a Library Book Borrowing API Using Spring Boot?
Interview Question:
A library needs a REST API to allow members to borrow books. Each book contains the following details:
- 1. ID
- 2. Title
- 3. Author
- 4. Available Copies
Write a Spring Boot application that allows a member to borrow a book only when copies are available.
Answer:
To develop this functionality, we can use Spring Boot, Spring Data JPA, and a relational database.
First, we need to create a Book entity to represent the book details in the database. We also need a repository interface to perform database operations.
Step 1: Create the Book Entity
An entity in Spring Boot represents a database table. We can use the @Entity annotation to tell JPA that the Book class should be mapped to a database table.
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private int availableCopies;
public Book() {
}
public Book(String title, String author, int availableCopies) {
this.title = title;
this.author = author;
this.availableCopies = availableCopies;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public int getAvailableCopies() {
return availableCopies;
}
public void setAvailableCopies(int availableCopies) {
this.availableCopies = availableCopies;
}
}
Explanation:
- 1. @Entity: Marks the Book class as a database entity.
- 2. @Id: Defines the primary key of the table.
- 3. @GeneratedValue: Automatically generates the book ID.
- 4. title: Stores the book title.
- 5. author: Stores the author’s name.
- 6. availableCopies: Stores the number of copies currently available for borrowing.
Step 2: Create the Spring Data JPA Repository
After creating the entity, we need a repository to communicate with the database.
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
}
Here, JpaRepository provides commonly used database operations such as saving, updating, deleting, and finding records.
We do not need to write separate SQL queries for basic operations because Spring Data JPA provides these methods automatically.
How to Create a POST API in Spring Boot?
Interview Question:
Write a POST /api/books/{id}/borrow endpoint that reduces the available book copies by one whenever a member borrows a book.
Answer:
To create this API, we should separate the application logic into different layers.
- 1. Controller: Receives HTTP requests and returns responses.
- 2. Service: Handles the book borrowing business logic.
- 3. Repository: Communicates with the database.
This structure keeps the application organised and makes the code easier to maintain.
Step 1: Create the Book Service
The service class contains the logic for borrowing a book.
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class BookService {
private final BookRepository bookRepository;
public BookService(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
@Transactional
public Book borrowBook(Long id) {
Book book = bookRepository.findById(id)
.orElseThrow(() ->
new BookNotFoundException("Book not found"));
if (book.getAvailableCopies() <= 0) {
throw new BookNotAvailableException(
"No copies available for borrowing"
);
}
book.setAvailableCopies(
book.getAvailableCopies() - 1
);
return bookRepository.save(book);
}
}
Explanation:
- 1. The @Service annotation identifies this class as a service component.
- 2. The constructor injects the BookRepository dependency.
- 3. The findById() method searches for the book using its ID.
- 4. If the book does not exist, a BookNotFoundException is thrown.
- 5. The application checks whether available copies are greater than zero.
- 6. If no copies are available, a BookNotAvailableException is thrown.
- 7. If copies are available, the application reduces the count by one.
- 8. The save() method stores the updated book details in the database.
The @Transactional annotation ensures that the borrowing operation runs within a database transaction. However, additional concurrency protection may be needed if multiple members try to borrow the last available copy simultaneously.
Step 2: Create the REST Controller
Now, we need a controller to expose the borrowing API.
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService bookService;
public BookController(BookService bookService) {
this.bookService = bookService;
}
@PostMapping("/{id}/borrow")
public Book borrowBook(@PathVariable Long id) {
return bookService.borrowBook(id);
}
}
Explanation:
- 1. @RestController: Marks the class as a REST API controller.
- 2. @RequestMapping(“/api/books”): Defines the common API path.
- 3. @PostMapping(“/{id}/borrow”): Handles POST requests for borrowing books.
- 4. @PathVariable: Reads the book ID from the URL.
- 5. bookService.borrowBook(id): Calls the service method to process the borrowing request.
For example, when a member sends a POST request to:
POST /api/books/101/borrow
The application searches for book ID 101. If the book exists and copies are available, the application reduces the available copies by one.
How to Handle Custom Exceptions in Spring Boot?
Interview Question:
What happens if a member tries to borrow a book that does not exist? What if the book exists but no copies are available?
Handle these situations using custom exceptions and @ControllerAdvice. Return HTTP 404 when the book does not exist and HTTP 409 when no copies are available.
Answer:
In a REST API, errors should be handled properly so that clients receive meaningful HTTP status codes and messages.
Instead of returning a generic error for every problem, we can create custom exception classes for different situations.
In this example, we need two custom exceptions:
- 1. BookNotFoundException – Used when the requested book does not exist.
- 2. BookNotAvailableException – Used when the book exists but no copies are available.
Step 1: Create BookNotFoundException
public class BookNotFoundException extends RuntimeException {
public BookNotFoundException(String message) {
super(message);
}
}
This exception is thrown when the application cannot find the requested book in the database.
Step 2: Create BookNotAvailableException
public class BookNotAvailableException extends RuntimeException {
public BookNotAvailableException(String message) {
super(message);
}
}
This exception is thrown when the requested book exists, but its available copy count is zero.
Step 3: Handle Exceptions Using @ControllerAdvice
Now, we can create a global exception handler to manage these exceptions in one place.
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BookNotFoundException.class)
public ResponseEntity<String> handleBookNotFound(
BookNotFoundException ex) {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
@ExceptionHandler(BookNotAvailableException.class)
public ResponseEntity<String> handleBookNotAvailable(
BookNotAvailableException ex) {
return ResponseEntity
.status(HttpStatus.CONFLICT)
.body(ex.getMessage());
}
}
Explanation:
- 1. @RestControllerAdvice: Handles exceptions globally across REST controllers.
- 2. @ExceptionHandler: Specifies which exception a particular method should handle.
- 3. HttpStatus.NOT_FOUND: Returns HTTP status code 404 when the requested book does not exist.
- 4. HttpStatus.CONFLICT: Returns HTTP status code 409 when the book exists but cannot be borrowed because no copies are available.
- 5. ResponseEntity: Allows us to control the HTTP response status and response body.
Expected API Responses:
| Situation | HTTP Status | Response Message |
| Book does not exist | 404 Not Found | Book not found |
| No available copies | 409 Conflict | No copies available for borrowing |
| Book successfully borrowed | 200 OK | Updated book details |
Important Interview Point:
1. @ControllerAdvice helps manage application exceptions from a central location instead of writing separate exception-handling logic in every controller.
This makes the code easier to maintain and ensures that the API returns meaningful responses when something goes wrong.
Understanding entities, repositories, service classes, REST controllers, transactions, and custom exception handling will help you solve similar Spring Boot development questions in technical interviews.
PostgreSQL Interview Questions and Answers
PostgreSQL is a relational database management system used to store, organise, and retrieve application data. It is commonly used in backend development to manage information such as customers, orders, products, and transactions.
During a PostgreSQL interview, candidates may be asked to write SQL queries, retrieve records from multiple tables, calculate totals, and filter data based on specific conditions.
In this section, we will work with an e-commerce database containing two tables: customers and orders. Using these tables, we will understand how to retrieve customer order details and identify the customers who spend the most money.
Write an SQL Query to Find Each Customer’s Total Order Amount?
Interview Question:
An e-commerce application has the following two database tables:
Customers Table
| Column | Description |
| id | Unique customer ID |
| name | Customer name |
| city | Customer’s city |
Orders Table
| Column | Description |
| id | Unique order ID |
| customer_id | Customer ID associated with the order |
| order_date | Date of the order |
| total_amount | Total order amount |
Write an SQL query to display each customer’s name and their total order amount. The result should also include customers who have never placed an order, with their total amount displayed as 0.
Answer:
To solve this problem, we can use LEFT JOIN, SUM(), GROUP BY, and COALESCE().
First, we need to understand why these SQL operations are required.
- 1. LEFT JOIN: Retrieves all customers, including those who do not have matching orders.
- 2. SUM(): Calculates the total amount spent by each customer.
- 3. GROUP BY: Groups the orders based on each customer.
- 4. COALESCE(): Replaces NULL values with 0.
SQL Query:
SELECT
c.name,
COALESCE(SUM(o.total_amount), 0) AS total_order_amount
FROM customers c
LEFT JOIN orders o
ON c.id = o.customer_id
GROUP BY c.id, c.name;
Explanation:
- 1. SELECT c.name retrieves the customer name from the customers table.
- 2. COALESCE(SUM(o.total_amount), 0) calculates the total order amount and displays 0 when no matching order exists.
- 3. FROM customers c selects the customers table as the starting point.
- 4. LEFT JOIN orders o connects the customers table with the orders table.
- 5. ON c.id = o.customer_id matches each order with its respective customer.
- 6. GROUP BY c.id, c.name groups the results customer-wise.
Example:
Customers table:
| id | name | city |
| 1 | Rahul | Chennai |
| 2 | Priya | Bangalore |
| 3 | Arun | Hyderabad |
Orders table:
| id | customer_id | total_amount |
| 101 | 1 | 2000 |
| 102 | 1 | 1500 |
| 103 | 2 | 3000 |
Expected Output:
| name | total_order_amount |
| Rahul | 3500 |
| Priya | 3000 |
| Arun | 0 |
Why is LEFT JOIN important here?
If we use an INNER JOIN, customers who have never placed an order will not appear in the result.
By using LEFT JOIN, all customers are included, even when there is no matching record in the orders table. The COALESCE() function then displays 0 instead of NULL for those customers.
This is a common SQL interview problem because it tests your understanding of joins, aggregate functions, and NULL value handling.
Find the Top 3 Customers by Total Spending in the Last 30 Days
Interview Question:
Using the same customers and orders tables, write an SQL query to find the top 3 customers based on their total spending during the last 30 days.
Answer:
To solve this problem, we need to calculate the total amount spent by each customer within the last 30 days and display the three customers with the highest spending.
We can use the following SQL concepts:
- 1. JOIN to connect customers with their orders.
- 2. WHERE to filter orders based on the date.
- 3. SUM() to calculate the total spending.
- 4. GROUP BY to group orders by customer.
- 5. ORDER BY to arrange customers based on their total spending.
- 6. LIMIT to display only the top three customers.
SQL Query:
SELECT
c.name,
SUM(o.total_amount) AS total_spent
FROM customers c
INNER JOIN orders o
ON c.id = o.customer_id
WHERE o.order_date >= CURRENT_DATE - INTERVAL '30 days'
AND o.order_date < CURRENT_DATE + INTERVAL '1 day'
GROUP BY c.id, c.name
ORDER BY total_spent DESC
LIMIT 3;
Explanation:
- 1. SELECT c.name retrieves the customer name.
- 2. SUM(o.total_amount) calculates the total amount spent by each customer.
- 3. INNER JOIN connects the customers and orders tables using their customer IDs.
- 4. WHERE filters orders placed within the last 30 days, including today’s orders.
- 5. GROUP BY combines all matching orders belonging to the same customer.
- 6. ORDER BY total_spent DESC sorts customers from the highest spending amount to the lowest.
- 7. LIMIT 3 returns only the first three customers.
Example:
Orders placed within the selected period:
| Customer | Total Spending |
| Rahul | ₹15,000 |
| Priya | ₹12,000 |
| Arun | ₹9,000 |
| Karthik | ₹7,000 |
| Divya | ₹5,000 |
Expected Output:
| name | total_spent |
| Rahul | 15000 |
| Priya | 12000 |
| Arun | 9000 |
Why do we use ORDER BY DESC and LIMIT 3?
The ORDER BY DESC clause arranges the customers from the highest spending amount to the lowest. The LIMIT 3 clause then returns only the first three records.
Without these two clauses, the query may return all customers without arranging them according to their spending.
Important Interview Point:
In PostgreSQL, CURRENT_DATE returns the current date, while INTERVAL ’30 days’ represents a period of 30 days. Together, they help filter orders based on a date range.
Understanding JOIN, GROUP BY, SUM(), COALESCE(), date filtering, and ORDER BY is important for solving SQL-based interview questions.
Practise writing these queries with different table structures and conditions. This will help you become more comfortable with database operations and real-world SQL problems.
Full Stack Developer Debugging Interview Questions
Full-stack developers work with frontend, backend, and database technologies to build and maintain web applications. During technical interviews, candidates may be given real-world problems to test their debugging skills and ability to find practical solutions.
Consider an e-commerce application where customers sometimes create duplicate orders by clicking the Place Order button twice. Another problem occurs when two customers try to purchase the last available product simultaneously, causing the stock quantity in the database to become negative.
These situations involve React, backend APIs, and PostgreSQL database operations. Let’s understand each problem and how to solve it.
How to Prevent Duplicate Orders in a Shopping Application?
Interview Question:
In a shopping application, users sometimes click the Place Order button twice, resulting in two orders being created. How would you prevent this problem on the React side?
Answer:
When a user clicks the Place Order button, the frontend sends a request to the backend to create an order. If the user clicks the button again before the first request finishes, another request may be sent.
This can result in duplicate orders if both requests are processed successfully.
One way to prevent this problem is to disable the Place Order button immediately after the first click. We can use React’s useState hook to manage the submission status.
React Code Example:
import React, { useState } from "react";
function PlaceOrder() {
const [loading, setLoading] = useState(false);
const handlePlaceOrder = async () => {
if (loading) return;
setLoading(true);
try {
const response = await fetch("/api/orders", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
productId: 101,
quantity: 1
})
});
if (!response.ok) {
throw new Error("Unable to place order");
}
const data = await response.json();
alert("Order placed successfully!");
console.log(data);
} catch (error) {
alert(error.message);
} finally {
setLoading(false);
}
};
return (
<div>
<button
onClick={handlePlaceOrder}
disabled={loading}
>
{loading ? "Placing Order..." : "Place Order"}
</button>
</div>
);
}
export default PlaceOrder;
Explanation:
- 1. The useState hook manages whether an order submission is in progress.
- 2. When the user clicks the button, the handlePlaceOrder() function executes.
- 3. The application checks whether a submission is already running.
- 4. The setLoading(true) function updates the loading state.
- 5. The button becomes disabled while the API request is running.
- 6. After the request finishes, the finally block resets the loading state.
This prevents users from repeatedly clicking the button while the request is being processed.
However, disabling the button on the frontend alone does not completely prevent duplicate orders. We also need protection on the backend and database.
Why Is a Frontend-Only Solution Not Enough to Prevent Duplicate Orders?
Interview Question:
Why is disabling the Place Order button on the frontend not enough? What additional protection can you implement on the backend or database?
Answer:
Frontend validation improves the user experience, but it cannot guarantee that an order will be created only once.
There are several situations where duplicate requests can still reach the backend:
- 1. A user may send multiple requests using browser developer tools or an API testing tool.
- 2. A network issue may cause the client to retry a request.
- 3. Two requests may reach the server before the frontend updates the button state.
- 4. Another application or client may call the same order API directly.
5. To handle these situations, we can implement Idempotency on the backend.
What Is Idempotency?
Idempotency means that sending the same request multiple times should not create multiple effects. For an order API, repeated requests with the same idempotency key should return the original result instead of creating another order.
For example, when a customer clicks Place Order, the frontend can generate a unique idempotency key and send it along with the API request.
Example API Request:
POST /api/orders
Idempotency-Key: order-request-12345
Content-Type: application/json
The backend checks whether this key has already been processed.
- If the key is new, the backend processes the order and stores the result along with the key.
- If the same key is received again, the backend returns the previously stored result instead of creating another order.
The backend should store and check these keys safely using a database constraint or suitable transaction handling to prevent simultaneous requests from processing the same key.
Database-Level Protection:
We can also use database constraints to prevent duplicate records.
For example, if each order has a unique order reference, we can create a UNIQUE constraint on that column.
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
order_reference VARCHAR(100) UNIQUE,
product_id BIGINT,
quantity INTEGER
);
Here, the UNIQUE constraint prevents two order records from having the same order reference.
Important Interview Point:
Frontend button disabling, backend idempotency, and database constraints solve different parts of the problem.
The frontend prevents accidental repeated clicks, backend idempotency handles repeated requests, and database constraints provide an additional layer of protection against duplicate records.
Why Does Stock Become Negative in PostgreSQL?
Interview Question:
In an e-commerce application, two users try to purchase the last available item at almost the same time. Both orders are created, and the stock quantity in PostgreSQL becomes -1.
Why does this happen? Explain the problem using a timeline of two requests reading and writing the stock.
Answer:
This problem occurs because of a database concurrency issue called a Race Condition.
A race condition happens when two or more operations access and modify the same data at nearly the same time, and the final result depends on how those operations are executed.
Let’s understand this with an example.
Assume a product has only one item available in the database.
Initial stock quantity: 1
| Step | Request A (User 1) | Request B (User 2) |
| 1 | Reads stock = 1 | |
| 2 | Reads stock = 1 | |
| 3 | Checks that stock is available | Checks that stock is available |
| 4 | Reduces stock by 1 | |
| 5 | Reduces stock by 1 |
Both requests may pass the availability check because they read the same initial stock value.
One important clarification is that if both requests calculate and write the value 0 based on the original stock, the result is generally a lost update rather than -1.
Negative stock can occur when both requests independently decrement the current database value without an atomic availability check.
For example, both transactions may execute:
UPDATE products
SET stock = stock - 1
WHERE id = 101;
If both updates are allowed to execute without checking whether stock is still available, the final stock can become -1.
Why Does This Happen?
The application checks the available stock and updates it as separate operations. Without proper concurrency protection, two requests can both pass the availability check before either one completes the update.
This is why checking stock only in application code is not enough. We also need to protect the database operation.
How to Prevent Negative Stock in a Database?
Interview Question:
How would you prevent negative stock when multiple users try to purchase the same product simultaneously? Explain one solution using optimistic locking, pessimistic locking, or an atomic SQL update.
Answer:
There are different ways to prevent negative stock in PostgreSQL. Three commonly used approaches are optimistic locking, pessimistic locking, and atomic database updates.
Let’s understand each approach.
1. Optimistic Locking Using @Version
Optimistic locking is useful when multiple transactions may update the same record, but conflicts are expected to be relatively uncommon.
In Spring Data JPA, we can use the @Version annotation to maintain a version number for an entity.
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Version;
@Entity
public class Product {
@Id
private Long id;
private String name;
private int stock;
@Version
private Long version;
// Getters and setters
}
Whenever the product is updated, JPA checks the version number.
For example:
- 1. Request A reads stock as 1 and version as 0.
- 2. Request B also reads stock as 1 and version as 0.
- 3. Request A updates the stock to 0 and increments the version to 1.
- 4. Request B tries to update using the old version number 0.
- 5. The update fails because the version has already changed.
Spring Data JPA detects this conflict and throws an optimistic locking exception.
The application can then handle the exception and inform the second user that the product is no longer available.
2. Pessimistic Locking
Pessimistic locking prevents other transactions from modifying a particular database record while the current transaction is processing it.
In Spring Data JPA, we can use @Lock with PESSIMISTIC_WRITE.
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.repository.query.Param;
import org.springframework.data.jpa.repository.Query;
import jakarta.persistence.LockModeType;
import java.util.Optional;
public interface ProductRepository
extends JpaRepository<Product, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT p FROM Product p WHERE p.id = :id")
Optional<Product> findByIdForUpdate(
@Param("id") Long id
);
}
The service method can then check and update the stock within a transaction.
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class ProductService {
private final ProductRepository productRepository;
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
@Transactional
public void purchaseProduct(Long id) {
Product product = productRepository
.findByIdForUpdate(id)
.orElseThrow(() ->
new RuntimeException("Product not found")
);
if (product.getStock() <= 0) {
throw new RuntimeException("Out of stock");
}
product.setStock(product.getStock() - 1);
productRepository.save(product);
}
}
How Does It Work?
- 1. Request A locks the product record.
- 2. Request B must wait until Request A completes its transaction.
- 3. Request A checks the stock and reduces it from 1 to 0.
- 4. Request A completes the transaction and releases the lock.
- 5. Request B gets access to the updated record and sees that stock is 0.
- 6. Request B is rejected because no products are available.
This approach ensures that two transactions cannot simultaneously modify the same locked product record.
3. Atomic UPDATE Query
Another approach is to update the stock directly using a single SQL statement with a condition.
UPDATE products
SET stock = stock - 1
WHERE id = 101
AND stock > 0;
This query reduces the stock only when the product exists and its current stock is greater than zero.
PostgreSQL executes the update atomically. If two transactions attempt to purchase the last item, one transaction updates the stock to zero. The other waits for the row update to finish and then rechecks the condition. Since the stock is now zero, the second update affects no rows.
We can check the number of affected rows:
- If one row is updated, the purchase can proceed.
- If zero rows are updated, the product is unavailable or the product ID does not exist.
Which Approach Should You Choose?
| Approach | How It Works | Suitable Use |
| Optimistic Locking | Checks the entity version before updating | Applications with fewer update conflicts |
| Pessimistic Locking | Locks the database record during the transaction | Applications where conflicting updates need to wait |
| Atomic UPDATE | Checks and updates stock in one SQL statement | Simple stock deduction operations |
Important Interview Point:
A negative stock problem cannot be solved reliably using frontend validation alone. The backend and database must protect the stock update against concurrent requests.
For a simple stock deduction, an atomic UPDATE query with stock > 0 is a direct solution. For more complex business operations, optimistic or pessimistic locking may be appropriate depending on the application requirements.
Understanding race conditions, database transactions, locking mechanisms, and atomic updates will help you solve similar debugging problems in full-stack development interviews.
Final Thoughts
Preparing for the OneBase.AI interview requires more than memorising technical concepts. You should be able to write code, solve practical problems, understand database queries, and explain how you approach real-world challenges. Focus on strengthening your React, Spring Boot, PostgreSQL, and full-stack development skills through regular practice.
If you are looking to build these skills with practical, project-based learning, Payilagam can help you take the next step in your IT career. As a Best Software Training Institute in Chennai, Payilagam offers industry-focused courses, including React JS Training in Chennai, Full Stack Training in Chennai, and SQL Training in Chennai. Keep practising, work on real-time projects, and prepare consistently to improve your confidence and technical skills for upcoming interviews.
Learn! Build! Get Hired!
Frequently Asked Questions About OneBase.AI Interview Questions
What technical topics are covered in OneBase.AI interview preparation?
The technical questions covered in this interview preparation include four important areas of full-stack development: React, Spring Boot, PostgreSQL, and full-stack debugging. These topics test your ability to build components, develop REST APIs, write SQL queries, handle database operations, and solve application-level problems.
What React concepts should freshers prepare for interviews?
Freshers should understand important React concepts such as functional components, JSX, props, state management, and React Hooks. Pay special attention to useState, useEffect, API integration, event handling, conditional rendering, loading states, error handling, and debouncing.
What is debouncing in React?
Debouncing is a technique that delays the execution of a function until the user stops performing an action for a specified period. In React, it is commonly used in search fields to avoid sending API requests after every keystroke. For example, an application can wait 500 milliseconds after the user stops typing before sending the search request.
How do you handle API errors in React?
You can handle API errors using try, catch, and finally blocks with async/await. The catch block handles errors, while the finally block executes after the request completes. You can also use a state variable to store and display an error message to the user.
What is Spring Data JPA?
Spring Data JPA is a part of the Spring ecosystem that simplifies database operations in Java applications. It provides repository interfaces with built-in methods to save, update, delete, and retrieve database records. By extending JpaRepository, developers can perform common database operations without writing separate SQL queries for every task.
How do you handle exceptions in Spring Boot?
In Spring Boot, exceptions can be handled using custom exception classes, @ExceptionHandler, and @ControllerAdvice. Custom exceptions represent specific application errors, while @ControllerAdvice provides a central location to handle exceptions from multiple controllers. This approach helps return meaningful error messages and appropriate HTTP status codes.
What is the difference between HTTP 404 and 409?
HTTP 404 and 409 represent different types of client errors.
- 404 Not Found: Returned when the requested resource does not exist. For example, when a user tries to borrow a book that is not available in the database.
- 409 Conflict: Returned when a request conflicts with the current state of a resource. For example, when a user tries to borrow a book that exists but has no available copies.
What is the difference between INNER JOIN and LEFT JOIN?
Both INNER JOIN and LEFT JOIN are used to retrieve data from multiple database tables, but they return different results.
- 1. INNER JOIN: Returns only records that have matching values in both tables.
- 2. LEFT JOIN: Returns all records from the left table, including records without matching values in the right table. Missing values from the right table are displayed as NULL.
For example, when retrieving customer orders, INNER JOIN excludes customers who have never placed an order, whereas LEFT JOIN includes all customers.
How do you find the top 3 customers using SQL?
You can use JOIN, SUM(), GROUP BY, ORDER BY, and LIMIT to find the top three customers based on their total spending.
SELECT
c.name,
SUM(o.total_amount) AS total_spent
FROM customers c
INNER JOIN orders o
ON c.id = o.customer_id
WHERE o.order_date >= CURRENT_DATE - INTERVAL '30 days'
AND o.order_date < CURRENT_DATE + INTERVAL '1 day'
GROUP BY c.id, c.name
ORDER BY total_spent DESC
LIMIT 3;
This query calculates each customer’s total spending during the selected period and displays the three customers with the highest order amounts.
What is a race condition in database systems?
A race condition occurs when multiple transactions access and modify the same data at nearly the same time. The final result may depend on how these operations are executed.
For example, if two customers try to purchase the last available product simultaneously, both requests may read the same stock value before updating it. Without proper concurrency protection, this can cause incorrect stock updates or negative stock.
How do you prevent duplicate orders in a full-stack application?
Duplicate orders can be prevented by implementing protection at multiple levels.
- 1. Frontend: Disable the Place Order button while a request is being processed.
- 2. Backend: Implement idempotency so repeated requests with the same key do not create multiple orders.
- 3. Database: Use unique constraints to prevent duplicate order references.
Using these methods together provides better protection than relying only on frontend validation.
What is optimistic locking in Spring Boot?
Optimistic locking is a technique used to prevent conflicting updates when multiple transactions try to modify the same database record.
In Spring Boot with JPA, we can use the @Version annotation to maintain a version number for an entity. When one transaction updates the record, the version changes. If another transaction tries to update the same record using an older version, the update fails with an optimistic locking exception.
What is pessimistic locking?
Pessimistic locking prevents other transactions from modifying a database record while the current transaction is processing it.
In Spring Data JPA, we can use @Lock(LockModeType.PESSIMISTIC_WRITE) to lock a record during a transaction. Other transactions attempting to acquire the same write lock must wait until the current transaction completes.
This approach is useful when multiple users may try to update the same data simultaneously, such as purchasing the last available product.
How can you prevent negative stock in PostgreSQL?
You can prevent negative stock by using an atomic UPDATE query with a condition that checks whether stock is greater than zero.
UPDATE products
SET stock = stock - 1
WHERE id = 101
AND stock > 0;
This query reduces the stock only when the product has at least one available item. If another transaction has already purchased the last item, the condition will no longer be satisfied, and the update will affect zero rows.
You can also use optimistic locking or pessimistic locking to protect stock updates, depending on the application’s requirements.

