🖍️
Developer Note
  • Welcome
  • Git
    • Eslint & Prettier & Stylelint & Husky
  • Programming Language
    • JavaScript
      • Script Async vs Defer
      • Module
      • Const VS Let VS Var
      • Promise
      • Event Loop
      • Execution Context
      • Hoisting
      • Closure
      • Event Buddling and Capturing
      • Garbage Collection
      • This
      • Routing
      • Debounce and Throttle
      • Web Component
      • Iterator
      • Syntax
      • String
      • Array
      • Object
      • Proxy & Reflect
      • ProtoType
      • Class
      • Immutability
      • Typeof & Instanceof
      • Npm (Node package manager)
    • TypeScript
      • Utility Type
      • Type vs Interface
      • Any vs Unknown vs Never
      • Void and undefined
      • Strict Mode
      • Namespace
      • Enum
      • Module
      • Generic
    • Python
      • Local Development
      • Uv
      • Asyncio & Event loop
      • Context Manager
      • Iterator & Generator
      • Fast API
      • Pydantic & Data Class
    • Java
      • Compilation and Execution
      • Data Type
      • Enumeration
      • Data Structure
      • Try Catch
      • InputStream and OutputStream
      • Concurrent
      • Unicode Block
      • Build Tools
      • Servlet
      • Java 8
  • Coding Pattern
    • MVC vs MVVM
    • OOP vs Functional
    • Error Handling
    • MVC vs Flux
    • Imperative vs Declarative
    • Design Pattern
  • Web Communication
    • REST API
      • Web Hook
      • CORS issue
    • HTTPS
    • GraphQL
      • REST API vs GraphQL
      • Implementation (NodeJS + React)
    • Server-Sent Event
    • Web Socket
    • IP
    • Domain Name System (DNS)
  • Frontend
    • Progressive Web App (PWA)
    • Single Page & Multiple Page Application
    • Search Engine Optimiaztion (SEO)
    • Web bundling & Micro-frontend
      • Webpack
        • Using Webpack to build React Application
        • Using Webpack to build react library
      • Vite
      • Using rollup to build react library
      • Implementing micro frontend
    • Web Security
      • CSRF & Nonce
      • XSS
      • Click hijacking
    • Cypress
    • CSS
      • Core
        • Box Model
        • Inline vs Block
        • Flexbox & Grid
        • Pseudo Class
        • Position
      • Tailwind CSS
        • Shadcn
      • CSS In JS
        • Material UI
    • React
      • Core
        • Component Pattern
        • React Lazy & Suspense
        • React Portal
        • Error Boundary
        • Rendering Methods
        • Environment Variable
        • Conditional CSS
        • Memo
        • Forward Reference
        • High Order Component (HOC) & Custom Hook
        • TypeScript
      • State Management
        • Redux
        • Recoil
        • Zustand
      • Routing
        • React Router Dom
      • Data Fetching
        • Axios & Hook
        • React Query
        • Orval
      • Table
        • React Table
      • Form & Validation
        • React Hook Form
        • Zod
      • NextJS
        • Page Router
        • App Router
      • React Native
    • Angular
    • Svelte
      • Svelte Kit
  • Backend
    • Cache
      • Browser Cache
      • Web Browser Storage
      • Proxy
      • Redis
    • Rate limit
    • Monitoring
      • Logging
      • Distributed Tracing
    • Load Test
    • Encryption
    • Authentication
      • Password Protection
      • Cookie & Session
      • JSON Web Token
      • SSO
        • OAuth 2.0
        • OpenID Connect (OIDC)
        • SAML
    • Payment
      • Pre-built
      • Custom
    • File Handling
      • Upload & Download (Front-end)
      • Stream & Buffer
    • Microservice
      • API Gateway
      • Service Discovery
      • Load Balancer
      • Circuit Breaker
      • Message Broker
      • BulkHead & Zipkin
    • Elastic Search
    • Database
      • SQL
        • Group By vs Distinct
        • Index
        • N + 1 problem
        • Normalization
        • Foreign Key
        • Relationship
        • Union & Join
        • User Defined Type
      • NOSQL (MongoDB)
      • Transaction
      • Sharding
      • Lock (Concurrency Control)
    • NodeJS
      • NodeJS vs Java Spring
      • ExpressJS
      • NestJS
        • Swagger
        • Class Validator & Validation Pipe
        • Passport (Authentication)
      • Path Module
      • Database Connection
        • Integrating with MYSQL
        • Sequalize
        • Integrating with MongoDB
        • Prisma
        • MikroORM
        • Mongoose
      • Streaming
      • Worker Thread
      • Passport JS
      • JSON Web Token
      • Socket IO
      • Bull MQ
      • Pino (Logging)
      • Yeoman
    • Spring
      • Spring MVC
      • Spring REST
      • Spring Actuator
      • Aspect Oriented Programming (AOP)
      • Controller Advice
      • Filter
      • Interceptor
      • Concurrent
      • Spring Security
      • Spring Boot
      • Spring Cloud
        • Resilience 4j
      • Quartz vs Spring Batch
      • JPA and Hibernate
      • HATEOS
      • Swagger
      • Unit Test (Java Spring)
      • Unit Test (Spring boot)
  • DevOp
    • Docker
    • Kubernetes
      • Helm
    • Nginx
    • File System
    • Cloud
      • AWS
        • EC2 (Virtual Machine)
        • Network
        • IAM
          • Role-Service Binding
        • Database
        • Route 53
        • S3
        • Message Queue
        • Application Service
        • Serverless Framework
        • Data Analysis
        • Machine Learning
        • Monitoring
        • Security
      • Azure
        • Identity
        • Compute Resource
        • Networking
        • Storage
        • Monitoring
      • Google Cloud
        • IAM
          • Workload Identity Federation
        • Compute Engine
        • VPC Network
        • Storage
        • Kubernetes Engine
        • App Engine
        • Cloud function
        • Cloud Run
        • Infra as Code
        • Pub/Sub
    • Deployment Strategy
    • Jenkins
    • Examples
      • Deploy NextJS on GCP
      • Deploy Spring on Azure
      • Deploy React on Azure
  • Domain Knowledge
    • Web 3
      • Blockchain
      • Cryptocurrency
    • AI
      • Prompt
      • Chain & Agent
      • LangChain
      • Chunking
      • Search
      • Side Products
Powered by GitBook
On this page
  • Introduction
  • Lifecycle
  • ACID
  • Atomicity(A)
  • Consistency(C)
  • Isolation(I)
  • Durability(D)
  • Implementation (With Sequalize)
  • Isolation
  • References

Was this helpful?

  1. Backend
  2. Database

Transaction

PreviousNOSQL (MongoDB)NextSharding

Last updated 10 months ago

Was this helpful?

Introduction

  • It is a sequence of multiple operations performed on a database, and all served as a single logical unit of work — taking place wholly or not at all.

  • For example, User A sell books to User B, there are several operations, update the book records, update the user A and user B's pocket money and quantity of book. These operations are in a transaction

Lifecycle

  • Active states: It is the first state during the execution of a transaction. A transaction is active as long as its instructions (read or write operations) are performed.

  • Partially committed: A change has been executed in this state, but the database has not yet committed the change on disk. In this state, data is stored in the memory buffer, and the buffer is not yet written to disk.

  • Committed: In this state, all the transaction updates are permanently stored in the database. Therefore, it is not possible to rollback the transaction after this point.

  • Failed: If a transaction fails or has been aborted in the active state or partially committed state, it enters into a failed state.

  • Terminated state: This is the last and final transaction state after a committed or aborted state. This marks the end of the database transaction life cycle.

ACID

Atomicity(A)

  • Atomicity in terms of a transaction means all or nothing. When a transaction is committed, the database either completes the transaction successfully or rolls it back so that the database returns to its original state.

Consistency(C)

  • One of the key advantages of using a transaction is maintaining data integrity, regardless of whether it succeeds or fails. Transactions can only alter affected data in a way that is authorized by the database engine, ensuring that a consistent view of the data is maintained at all times.

Isolation(I)

  • With multiple concurrent transactions running at the same time, each transaction should be kept independent without affecting other transactions executing simultaneously

Durability(D)

  • Durability means that a successful transaction commit will survive permanently.

Implementation (With Sequalize)

const t = await sequelize.transaction();

try {
  // Then, we do some calls passing this transaction as an option:
  const user = await User.create({
    firstName: 'Bart',
    lastName: 'Simpson'
  }, { transaction: t });

  await user.addSibling({
    firstName: 'Lisa',
    lastName: 'Simpson'
  }, { transaction: t });

  // If the execution reaches this line, no errors were thrown.
  // We commit the transaction.
  await t.commit();

} catch (error) {

  // If the execution reaches this line, an error was thrown.
  // We rollback the transaction.
  await t.rollback();
}

Isolation

Introduction

  • Isolation describes how changes applied by concurrent transactions are visible to each other.

  • Each isolation level prevents zero or more concurrency side effects on a transaction:

    • Dirty read: A dirty read occurs when a transaction reads data that has not yet been committed. For example, suppose transaction 1 updates a row. Transaction 2 reads the updated row before transaction 1 commits the update. If transaction 1 rolls back the change, transaction 2 will have read data that is considered never to have existed.

    • Non-repeatable read: A non-repeatable read occurs when a transaction reads the same row twice but gets different data each time. For example, suppose transaction 1 reads a row. Transaction 2 updates or deletes that row and commits the update or delete. If transaction 1 rereads the row, it retrieves different row values or discovers that the row has been deleted.

    • Phantom read: A phantom is a row that matches the search criteria but is not initially seen. For example, suppose transaction 1 reads a set of rows that satisfy some search criteria. Transaction 2 generates a new row (through either an update or an insert) that matches the search criteria for transaction 1. If transaction 1 re-executes the statement that reads the rows, it gets a different set of rows.

Read Un-commit

  • Transactions are not isolated from each other.

Read Committed

  • Data modification can only be read after the transaction is committed.

  • The transaction waits until rows write-locked by other transactions are unlocked; this prevents it from reading any "dirty" data

-- Set isolation level
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

-- Start transaction 1
BEGIN TRANSACTION;

-- Read data
SELECT * FROM Products;

-- Wait for a few seconds (simulate concurrent transaction)

-- Start transaction 2
BEGIN TRANSACTION;

-- Modify data
UPDATE Products SET ProductName = 'New Name' WHERE ProductID = 1;

-- Commit transaction 2
COMMIT;

-- Read data again within transaction 1
SELECT * FROM Products;

-- Commit or rollback transaction 1
COMMIT;
  • Transaction 1 reads the data from the "Products" table, and while it is still active, transaction 2 modifies a record. After transaction 2 commit, The READ COMMITTED isolation level allows transaction 1 to see the changes made by transaction 2 when it reads the data again.

Repeatable Read

  • Data read during the transaction stays the same as the transaction starts.

  • Prevents dirty, and non-repeatable reads. So we are not affected by uncommitted changes in concurrent transactions

  • Also, when we re-query for a row, we don't get a different result. However, in the re-execution of range-queries, we may get newly added or removed rows.

-- Set isolation level
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;

-- Start transaction 1
BEGIN TRANSACTION;

-- Read data
SELECT * FROM Products;

-- Wait for a few seconds (simulate concurrent transaction)

-- Start transaction 2
BEGIN TRANSACTION;

-- Modify data
UPDATE Products SET ProductName = 'New Name' WHERE ProductID = 1;

-- Commit transaction 2
COMMIT;

-- Read data again within transaction 1
SELECT * FROM Products;

-- Commit or rollback transaction 1
COMMIT;
  • transaction 1 reads the data from the "Products" table, and while it is still active, transaction 2 modifies a record. The REPEATABLE READ isolation level ensures that transaction 1 sees the same data , even if transaction 2 made changes. The second read within transaction 1 will still show the original data

Serializable

  • It prevents all mentioned concurrency side effects, but can lead to the lowest concurrent access rate because it executes concurrent calls sequentially.

-- Set isolation level
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

-- Start transaction 1
BEGIN TRANSACTION;

-- Read data
SELECT * FROM Products;

-- Wait for a few seconds (simulate concurrent transaction)

-- Start transaction 2
BEGIN TRANSACTION;

-- Modify data
INSERT INTO Products (id, "ProductName")  Values (3, 'Product3');

-- Commit transaction 2
COMMIT;

-- Read data again within transaction 1
SELECT * FROM Products;

-- Commit or rollback transaction 1
COMMIT;
  • transaction 1 reads the data from the "Products" table, and while it is still active, transaction 2 insert s a record. The SERIALIZABLE isolation level ensures that transaction 1 sees the same snapshot of the data it read initially, even if transaction 2 made changes. The second read within transaction 1 will still show the original data.

References

LogoWhat is a database transaction?Fauna
LogoTransactions | Sequelize