ADO.NET Core Tutorial
Lesson 35 of 100 35% of course

Retry Logic — Complete Guide

1 · 9 min · 5/24/2026

Learn Retry Logic — Complete Guide in our free ADO.NET Core Tutorial series. Step-by-step explanations, examples, and interview tips on Toolliyo Academy.

Sign in to track progress and bookmarks.

Retry Logic — Complete Guide — ShopNest.DataAccess
Article 35 of 100 · Module 4: Transactions and Error Handling · Reporting
Target keyword: retry logic ado.net core · Read time: ~24 min · .NET: 8 / 9 · Project: ShopNest.DataAccess — Reporting

Introduction

Retry Logic — Complete Guide is essential for .NET architects building ShopNest.DataAccess — Enterprise High-Performance Data Platform — Toolliyo's 100-article ADO.NET Core master path covering SqlConnection, stored procedures, transactions, connection pooling, performance tuning, ASP.NET Core integration, and senior interview preparation. Every article includes minimum 2 detailed enterprise real-world examples (banking transfers, ERP reporting, insurance batch, legacy modernization) in different business domains.

In Indian delivery projects (TCS, Infosys, Wipro), interviewers expect retry logic with real ICICI-style banking, TCS ERP reporting, insurance batch processing, or government legacy modernization examples — not toy animal demos. This article delivers two mandatory enterprise examples on Reporting.

After this article you will

  • Explain Retry Logic in plain English and in SQL Server and high-performance data access terms
  • Implement retry logic in ShopNest.DataAccess — Enterprise High-Performance Data Platform (Reporting)
  • Compare the wrong approach vs the production-ready enterprise approach
  • Answer fresher, mid-level, and senior ADO.NET and SQL Server interview questions confidently
  • Connect this lesson to Article 36 and the 100-article ADO.NET Core roadmap

Prerequisites

Concept deep-dive

Level 1 — Analogy

Retry Logic on ShopNest.DataAccess adds high-performance SQL Server data access for enterprise modules.

Level 2 — Technical

Retry Logic integrates with the LINQ query layer: write queries against IEnumerable or IQueryable, understand deferred execution, project to DTOs for ShopNest.DataAccess reports. On ShopNest.DataAccess this powers Reporting without coupling UI to database internals.

Level 3 — Architecture

[Browser] → [HTTPS/Kestrel] → [Middleware Pipeline]
  → [Routing] → [Controller Action] → [Service Layer]
  → [EF Core / Identity] → [Razor View Engine] → [HTML Response]

Common misconceptions

❌ MYTH: Retry Logic is only needed for large enterprise apps.
✅ TRUTH: ShopNest.DataAccess starts simple — add complexity when traffic, team size, or compliance demands it.

❌ MYTH: Web API 2 and ASP.NET Core Web API are the same.
✅ TRUTH: Push filtering, sorting, and aggregation to IQueryable so SQL Server does the work — avoid client-side evaluation.

❌ MYTH: You can call .ToList() first and filter in memory — it works for small data.
✅ TRUTH: Never materialize early on large datasets — filter and project in IQueryable, watch for multiple enumeration.

Project structure

ShopNest.DataAccess/
├── ShopNest.DataAccess/
├── src/
│   ├── ShopNest.DataAccess.Api/       ← ASP.NET Core Web API
│   ├── ShopNest.DataAccess.Core/      ← Repository interfaces
│   ├── ShopNest.DataAccess.AdoNet/    ← SqlConnection, SPs, transactions
│   ├── ShopNest.DataAccess.Reports/   ← Streaming readers, GL reports
│   └── ShopNest.DataAccess.Tests/     ← Integration tests (Testcontainers SQL)
├── sql/
│   ├── migrations/
│   └── stored-procedures/
└── docker-compose.yml                 ← SQL Server 2022 + Redis

Step-by-Step Implementation — ShopNest (Reporting)

Follow the prompt template: create project → core classes → interfaces → pattern implementation → client code → run → enterprise refactor.

Step 1 — The wrong way

// ❌ BAD — fat controller, no ViewModel, sync DB call
public IActionResult Index()
{
    return _context.Products.Find(id); // sync, exposes entity, no auth
}

Step 2 — The right way

// ✅ CORRECT — Retry Logic on ShopNest (Reporting)
var results = await _context.Products
    .Where(p => p.IsPublished && p.CategoryId == categoryId)
    .OrderBy(p => p.Name)
    .Select(p => new ProductReportDto { Id = p.Id, Name = p.Name, Revenue = p.Orders.Sum(o => o.Total) })
    .ToListAsync(ct);

Step 3 — Apply Retry Logic

var query = _context.Products.AsNoTracking();
var page = await query.Skip((pageNum - 1) * pageSize).Take(pageSize).ToListAsync();
dotnet run --project ShopNest.DataAccess.Api
# Verify Retry Logic — check SQL Server Management Studio and connection pool metrics and integration tests pass

SQL performance and connection management — Retry Logic

  • Connection pooling — default enabled; never disable without load testing; watch pool exhaustion (error 10053/10054)
  • Parameterized queries — always use SqlParameter; prevents SQL injection and enables plan cache reuse
  • Async — ExecuteReaderAsync/ExecuteNonQueryAsync free thread pool under load
  • CommandBehavior.SequentialAccess — stream large BLOB/text columns without loading full row into memory
  • Indexes — align with WHERE/JOIN columns; use SQL Server DMVs to find missing indexes

Real-World Example 1 — TCS ERP Monthly GL Reporting

MANDATORY enterprise scenario (Enterprise ERP): Retry Logic in ShopNest.DataAccess Reporting.

Business problem

Finance teams run month-end General Ledger reports across 200+ cost centers. Report queries join 12 tables and return 2M rows — EF Core materializes entire graphs into memory. ADO.NET SqlDataReader streams rows to CSV/PDF generators with constant memory.

Architecture

[Report Scheduler] → [GlReportRepository]
  → EXEC usp_GenerateMonthlyGL @Year, @Month, @CostCenterId
  → SqlDataReader forward-only stream → IAsyncEnumerable
  → Bulk copy to staging → SSRS / Excel export
Read uncommitted avoided; NOLOCK only on read replica for analytics.

Production ADO.NET code

public async IAsyncEnumerable<GlLineDto> StreamGlReportAsync(int year, int month, [EnumeratorCancellation] CancellationToken ct)
{
    await using var conn = new SqlConnection(_readReplicaConnectionString);
    await conn.OpenAsync(ct);
    await using var cmd = new SqlCommand("usp_GenerateMonthlyGL", conn)
    {
        CommandType = CommandType.StoredProcedure
    };
    cmd.Parameters.Add("@Year", SqlDbType.Int).Value = year;
    cmd.Parameters.Add("@Month", SqlDbType.Int).Value = month;

    await using var reader = await cmd.ExecuteReaderAsync(CommandBehavior.SequentialAccess, ct);
    while (await reader.ReadAsync(ct))
    {
        yield return new GlLineDto(
            reader.GetString(0),
            reader.GetDecimal(1),
            reader.GetDateTime(2));
    }
}

Outcome

Memory flat at 80MB for 2M-row report vs 1.2GB EF Core ToList(); report runtime cut from 14 min to 3 min.

Real-World Example 2 — Government Pension Legacy Modernization

MANDATORY enterprise scenario (Government / PSU): Retry Logic in ShopNest.DataAccess Reporting.

Business problem

20-year-old VB6 + inline SQL pension system migrated to ASP.NET Core. ADO.NET wraps existing stored procedures — no ORM rewrite — minimizing regression risk while adding connection pooling and async I/O.

Architecture

Legacy SPs (unchanged) ← AdoNetLegacyBridge → ASP.NET Core Web API
  → Repository per bounded context (Pension, Disbursement, Audit)
  → Strangler Fig: new modules EF Core, legacy modules ADO.NET

Production ADO.NET code

// Bridge pattern — call legacy SP by name
public async Task<PensionDetail?> GetPensionAsync(string pensionId, CancellationToken ct)
{
    const string sql = "EXEC dbo.usp_GetPensionDetail @PensionId";
    await using var conn = new SqlConnection(_legacyConnStr);
    await using var cmd = new SqlCommand(sql, conn);
    cmd.Parameters.Add("@PensionId", SqlDbType.VarChar, 15).Value = pensionId;
    await conn.OpenAsync(ct);
    await using var r = await cmd.ExecuteReaderAsync(ct);
    return r.Read() ? MapPension(r) : null;
}

Outcome

Migration delivered in 8 months vs 24-month full rewrite estimate; 99.2% SP compatibility on day one.

ADO.NET with ASP.NET Core — Retry Logic

Register IOrderRepository implementations in DI as Scoped. Never hold SqlConnection across requests. Use IConfiguration for connection strings; User Secrets locally, Azure Key Vault in production.

builder.Services.AddScoped();
builder.Services.AddHealthChecks().AddSqlServer(connectionString);

Stored procedures and SQL safety

Enterprise ShopNest modules use versioned stored procedures (usp_ prefix). Never concatenate user input — always SqlParameter. Log slow queries (>500ms) with Serilog.

Common errors & fixes

🔴 Mistake 1: Fat controllers with EF Core queries inline
Fix: Move data access to services/repositories; keep controllers thin.

🔴 Mistake 2: Calling .ToList() too early materializing millions of rows into memory
Fix: Defer execution — build IQueryable pipeline, then ToListAsync() once at the end.

🔴 Mistake 3: Filtering in memory after .ToList() instead of in the database query
Fix: Keep filters in IQueryable, use Select projection, paginate with Skip/Take before materialization.

🔴 Mistake 4: Hard-coding connection strings in controllers
Fix: Use appsettings.json + User Secrets locally; Azure Key Vault in production.

Best practices

  • 🟢 Use async/await end-to-end for database and I/O calls
  • 🟢 Register DbContext as Scoped; avoid capturing it in singletons
  • 🟡 Use IQueryable until the last moment; avoid multiple enumeration; project with Select before ToList
  • 🟡 Prefer method syntax for complex chains; use query syntax for joins when readability wins
  • 🔴 Log structured data with Serilog — include OrderId, UserId, not passwords
  • 🔴 Use HTTPS, secure cookies, and authorization policies in production

Interview questions

Fresher level

Q1: What is Retry Logic in ASP.NET Core MVC?
A: Retry Logic is a core MVC capability used in ShopNest.DataAccess for Reporting. Explain in one sentence, then describe controller/view/service placement.

Q2: How would you implement Retry Logic on a TCS-style delivery project?
A: Deferred execution, IQueryable pipelines, Select projection, Skip/Take pagination, and SQL logging in development.

Q3: IEnumerable vs IQueryable — when to use which?
A: IEnumerable for in-memory collections; IQueryable for EF Core database queries that translate to SQL.

Mid / senior level

Q4: Explain LINQ deferred execution and query translation briefly.
A: LINQ → Expression Tree → IQueryProvider → SQL (EF) or Iterator (in-memory) → Results.

Q5: Common production mistake with this topic?
A: Skipping validation, exposing secrets in Git, or untested edge cases (null model, unauthorized user).

Q6: .NET LINQ vs SQL — when to push logic to database?
A: Core is cross-platform, faster, cloud-ready; Framework is maintenance mode on Windows/IIS.

Coding round

Implement Retry Logic for ShopNest Reporting: show interface, concrete class, DI registration, and xUnit test with mock.

public class RetryLogicPatternTests
{
    [Fact]
    public async Task ExecuteAsync_ReturnsSuccess()
    {
        var mock = new Mock();
        mock.Setup(s => s.ExecuteAsync(It.IsAny(), default))
            .ReturnsAsync(Result.Success("test-id"));
        var result = await mock.Object.ExecuteAsync(new Request("test-id"));
        Assert.True(result.IsSuccess);
    }
}

Summary & next steps

  • Article 35: Retry Logic — Complete Guide
  • Module: Module 4: Transactions and Error Handling · Level: INTERMEDIATE
  • Applied to ShopNest.DataAccess — Reporting

Previous: Deadlock Handling — Complete Guide
Next: Exception Handling — Complete Guide

Practice: Add one small feature using today's pattern — commit with feat(adonet): article-35.

FAQ

Q1: What is Retry Logic?

Retry Logic helps ShopNest.DataAccess implement Reporting using C# 12 LINQ with EF Core where applicable.

Q2: Do I need Visual Studio?

No — .NET 8 SDK with VS Code + C# Dev Kit works. Visual Studio 2022 Community is recommended for MVC scaffolding.

Q3: Is this asked in Indian IT interviews?

Yes — MVC topics from Modules 1–6 appear in TCS, Infosys, Wipro campus drives; architecture modules in lateral hires.

Q4: Which .NET version?

Examples target .NET 8 LTS and .NET 9 with C# 12+ syntax.

Q5: How does this fit ShopNest.DataAccess?

Article 35 adds retry logic to Reporting. By Article 100 you have a portfolio-ready ShopNest.DataAccess enterprise database layer.

Test your knowledge

Quizzes linked to this course—pass to earn certificates.

Browse all quizzes
ADO.NET Core Tutorial

On this page

Introduction After this article you will Prerequisites Concept deep-dive Level 1 — Analogy Level 2 — Technical Level 3 — Architecture Project structure Step-by-Step Implementation — ShopNest (Reporting) Step 1 — The wrong way Step 2 — The right way Step 3 — Apply Retry Logic SQL performance and connection management — Retry Logic Real-World Example 1 — TCS ERP Monthly GL Reporting Business problem Architecture Production ADO.NET code Outcome Real-World Example 2 — Government Pension Legacy Modernization Business problem Architecture Production ADO.NET code Outcome ADO.NET with ASP.NET Core — Retry Logic Stored procedures and SQL safety Common errors &amp; fixes Best practices Interview questions Fresher level Mid / senior level Coding round Summary &amp; next steps FAQ Q1: What is Retry Logic? Q2: Do I need Visual Studio? Q3: Is this asked in Indian IT interviews? Q4: Which .NET version? Q5: How does this fit ShopNest.DataAccess?
Module 1: ADO.NET Fundamentals
Introduction to ADO.NET Core — Complete Guide ADO.NET Architecture — Complete Guide ADO.NET vs EF Core vs Dapper — Complete Guide SQL Server Setup — Complete Guide Connection Strings — Complete Guide SqlConnection — Complete Guide SqlCommand — Complete Guide SqlDataReader — Complete Guide DataSet — Complete Guide DataTable — Complete Guide
Module 2: CRUD Operations
Insert Operations — Complete Guide Select Operations — Complete Guide Update Operations — Complete Guide Delete Operations — Complete Guide Batch Operations — Complete Guide Async Operations — Complete Guide Parameterized Queries — Complete Guide SQL Injection Prevention — Complete Guide Bulk Insert — Complete Guide Pagination — Complete Guide
Module 3: Stored Procedures
Introduction to Stored Procedures — Complete Guide Creating Stored Procedures — Complete Guide Executing Stored Procedures — Complete Guide Input Parameters — Complete Guide Output Parameters — Complete Guide Return Values — Complete Guide Dynamic SQL — Complete Guide Performance Optimization — Complete Guide Reporting Procedures — Complete Guide Enterprise Transaction Procedures — Complete Guide
Module 4: Transactions and Error Handling
SQL Transactions — Complete Guide Commit and Rollback — Complete Guide Isolation Levels — Complete Guide Deadlock Handling — Complete Guide Retry Logic — Complete Guide Exception Handling — Complete Guide Distributed Transactions — Complete Guide Logging — Complete Guide Audit Trails — Complete Guide ACID Principles — Complete Guide
Module 5: Performance Optimization
Connection Pooling — Complete Guide Async Database Operations — Complete Guide Query Optimization — Complete Guide SQL Indexing — Complete Guide DataReader Optimization — Complete Guide Streaming Data — Complete Guide Batch Processing — Complete Guide Bulk Operations — Complete Guide Memory Optimization — Complete Guide High-Performance APIs — Complete Guide
Module 6: ASP.NET Core Integration
ADO.NET with ASP.NET Core MVC — Complete Guide ADO.NET with ASP.NET Core Web API — Complete Guide Repository Pattern — Complete Guide Clean Architecture — Complete Guide Dependency Injection — Complete Guide Configuration Management — Complete Guide DTO Mapping — Complete Guide Authentication Integration — Complete Guide Logging Integration — Complete Guide API Optimization — Complete Guide
Module 7: Advanced Enterprise Topics
CQRS with ADO.NET — Complete Guide Reporting Systems — Complete Guide Data Warehousing Concepts — Complete Guide Multi-Database Architecture — Complete Guide Read Replica Strategies — Complete Guide Distributed Systems — Complete Guide Event-Driven Systems — Complete Guide Background Services — Complete Guide Legacy System Modernization — Complete Guide Enterprise Reporting Dashboards — Complete Guide
Module 8: Testing and Debugging
Unit Testing — Complete Guide Integration Testing — Complete Guide Mocking Database Calls — Complete Guide SQL Profiling — Complete Guide Query Logging — Complete Guide Performance Profiling — Complete Guide Debugging Transactions — Complete Guide Deadlock Analysis — Complete Guide Monitoring SQL Performance — Complete Guide Production Diagnostics — Complete Guide
Module 9: Cloud and DevOps
Azure SQL — Complete Guide Dockerizing SQL Server — Complete Guide Kubernetes Database Setup — Complete Guide CI/CD for Database Projects — Complete Guide Database Migration Strategies — Complete Guide Backup and Restore — Complete Guide Disaster Recovery — Complete Guide Monitoring — Complete Guide Secrets Management — Complete Guide High Availability — Complete Guide
Module 10: Real-World Enterprise Projects
Banking Transaction System — Complete Guide ERP Reporting System — Complete Guide Inventory Management System — Complete Guide Hospital Management System — Complete Guide Financial Analytics Platform — Complete Guide Payment Processing System — Complete Guide CRM Reporting System — Complete Guide Multi-Tenant SaaS Database — Complete Guide High-Performance Order System — Complete Guide Enterprise Legacy Modernization — Capstone