pushoo-sharma / Database-Concurrency-Control

This project provides a practical example of implementing database concurrency control using Sequelize in a Node.js/Express application with a MySQL database. This implementation includes a production-ready API endpoint (POST /) that manages concurrent updates to a counter in the database.
1 stars 0 forks source link

Database Concurrency Control Example

This project demonstrates a simple example of implementing database concurrency control using Sequelize in a Node.js/Express application with a MySQL database.

Table of Contents

Introduction

This project showcases a Node.js/Express application that interacts with a MySQL database using Sequelize. The application includes a basic API endpoint (POST /) that increments a counter in the database.

Prerequisites

Before running the application, make sure you have the following installed:

Getting Started

  1. Clone the repository:

    git clone https://github.com/your-username/your-repo.git
  2. Install dependencies:

    cd your-repo
    npm install
  3. Configure the database credentials:

    Open TSroute.ts and replace the placeholder values with your actual database credentials:

    const sequelize = new Sequelize('your-database', 'your-username', 'your-password', {
        host: 'localhost',
        dialect: 'mysql',
    });
  4. Sync the model with the database:

    npm run sync
  5. Initialize the database with an initial count value:

    Open TSroute.ts and find the following code:

    // Add this code to initialize the database with a starting count value
    const initialCount = 10;
    await Count.create({ count: initialCount });
  6. Insert SQL script:

    -- Add this SQL command to initialize the database with a starting count value
    INSERT INTO counts (count) VALUES (10);
  7. Save the changes and run the script:

    npx ts-node src/app/server.ts

Understanding Database Concurrency Control

The main file TSroute.ts includes a POST endpoint that increments a counter in the database. It uses Sequelize for database interactions.

  1. The Count model is defined with two columns: id (primary key) and count.
  2. The POST endpoint finds the row with id = 1, increments the count value, and updates the database.

Executing the Script

To execute the script that simulates 1000 POST requests:


chmod +x execute_1000_times.sh
./execute_1000_times.sh