Skip to content

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

EF Core Two-Phase Commit Demo (.NET 8 + Docker)

This sample demonstrates a Two-Phase Commit (2PC) style transaction using .NET 8 and Entity Framework Core. It simulates a bank transfer between two separate SQL Server instances running in Docker containers.

Project Structure

2PC-Demo/
├── src/
│   ├── Contexts/           # Database context classes
│   │     BankAContext.cs
│   │     BankBContext.cs
│   │
│   ├── Models/            # Entity models
│   │     Account.cs
│   │
│   ├── Data/             # Database initialization
│   │     DbInitializer.cs
│   │
│   ├── Services/         # Business logic
│   │     BankTransferService.cs
│   │
│   ├── Program.cs        # Application entry point
│   ├── appsettings.json  # Configuration
│   └── TwoPhaseCommitDemo.csproj
│
└── docker-compose.yml    # Docker configuration

Features

  • Two-Phase Commit pattern implementation
  • Automatic database initialization and seeding
  • Simulated failure scenario for testing rollbacks
  • Clean separation of concerns (services, data, models)
  • Detailed console logging with Serilog

Running the Demo

1) Start the Databases

docker-compose up -d

Wait until both containers are healthy:

docker ps

2) Run the Demo

Success scenario:

cd src
dotnet run

Failure scenario (simulates error after first commit):

cd src
dotnet run --fail

What Happens?

  1. On startup:

    • Creates both databases if they don't exist
    • Seeds initial test accounts:
      • BankA: Account1 with 1000
      • BankB: Account2 with 500
  2. During transfer:

    • Attempts to transfer 100 from BankA to BankB
    • Uses transaction coordination to ensure consistency
    • Either both operations succeed or both rollback
  3. In failure scenario:

    • Simulates error after BankA update
    • Demonstrates automatic rollback
    • Ensures data consistency across both databases

Technical Notes

  • Uses SQL Server instances:
    • BankA on port 1433
    • BankB on port 1434
  • Data is reset on each run for clean demo
  • Uses TransactionScope for coordinating transactions
  • Detailed logging shows each phase of the 2PC process

Troubleshooting

  • Ensure Docker containers are running and healthy
  • Check if ports 1433 and 1434 are available
  • Verify SQL Server connection strings in appsettings.json
  • Look at console logs for detailed error information

About

Demonstrates Two-Phase Commit (2PC)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages