A NestJS application that demonstrates transaction handling for concurrent balance updates.
- Docker and Docker Compose
- Node.js (if running locally)
The project includes utility scripts in the scripts/ directory:
A helper script that initializes and starts the entire application:
# Make it executable
chmod +x scripts/start.sh
# Run the script
./scripts/start.shThis script:
- Creates
.envfile if it doesn't exist - Starts all services with Docker Compose
- Waits for services to initialize
- Shows the logs of running containers
Tests the application's concurrency handling by sending 10,000 simultaneous requests:
# Make it executable
chmod +x scripts/test-concurrency.sh
# Run the script
./scripts/test-concurrency.shThis script:
- Sends 10,000 concurrent requests to withdraw 2 units each
- Tracks successful and failed requests
- Verifies that exactly 5,000 requests succeed and 5,000 fail
- Displays test results
Note: The test script requires curl and jq to be installed.
- Clone the repository
- Navigate to the project directory
- Run the application:
docker-compose upThis will start both the PostgreSQL database and the NestJS application.
- Clone the repository
- Navigate to the project directory
- Install dependencies:
npm install- Create a
.envfile based on the provided example - Run the database:
docker-compose up postgres- Run migrations:
npm run migrate- Start the application:
npm run start:devUpdates a user's balance.
- URL:
/api/balance/update - Method:
POST - Body:
{ "userId": 1, "amount": 100 } - Success Response:
{ "userId": 1, "newBalance": 10100 } - Error Responses:
- 400 Bad Request:
{ "error": "Insufficient funds" } - 404 Not Found:
{ "error": "User not found" } - 500 Internal Server Error:
{ "error": "Internal server error" }
- 400 Bad Request:
The system is designed to handle concurrent requests that modify the same user's balance. When 10,000 requests try to withdraw 2 units each from a balance of 10,000, exactly 5,000 will succeed and 5,000 will fail with an "Insufficient funds" error.