Thursday, 12 March 2026

how to control duplicate order

 Controlling duplicate orders is a common challenge in distributed systems, APIs, and microservices (especially in .NET Core + Angular + SQL Server architectures like yours). Duplicate orders usually happen due to:

  • User clicking “Place Order” multiple times

  • Network retries from client or gateway

  • Message queue retries

  • Concurrency issues in DB

  • API being called twice

Below are the most effective real-world solutions used in production systems. 🚀


1️⃣ Use Idempotency Key (Best Practice for APIs)

An Idempotency Key ensures that even if the request is sent multiple times, only one order is created.

Flow

  1. Angular generates a unique key (GUID).

  2. Send it in API header.

Idempotency-Key: 123e4567-e89b-12d3-a456-426614174000
  1. API checks database/cache.

  • If key exists → return existing order.

  • If not → create order and store key.

Table Example

CREATE TABLE OrderRequests
(
    IdempotencyKey UNIQUEIDENTIFIER PRIMARY KEY,
    OrderId INT,
    CreatedDate DATETIME
)

.NET Core Example

[HttpPost]
public async Task<IActionResult> CreateOrder([FromHeader(Name="Idempotency-Key")] string key)
{
    var existing = await _db.OrderRequests
        .FirstOrDefaultAsync(x => x.IdempotencyKey == Guid.Parse(key));

    if(existing != null)
        return Ok(existing.OrderId);

    var order = new Order();
    _db.Orders.Add(order);
    await _db.SaveChangesAsync();

    _db.OrderRequests.Add(new OrderRequest
    {
        IdempotencyKey = Guid.Parse(key),
        OrderId = order.Id
    });

    await _db.SaveChangesAsync();

    return Ok(order.Id);
}

✅ Prevents duplicate orders even if API is called 10 times.


2️⃣ Unique Constraint in Database

Use unique index to prevent duplicate order creation.

Example:

CREATE UNIQUE INDEX UX_Order_User_Product
ON Orders(UserId, ProductId, OrderDate)

If duplicate request comes → SQL Server throws error.


3️⃣ Disable Button in Angular UI

Prevent multiple clicks.

isSubmitting = false;

placeOrder() {
  if(this.isSubmitting) return;

  this.isSubmitting = true;

  this.orderService.placeOrder().subscribe({
    next: () => this.isSubmitting = false,
    error: () => this.isSubmitting = false
  });
}

HTML:

<button [disabled]="isSubmitting">
Place Order
</button>

4️⃣ Optimistic Concurrency Control

Use RowVersion / Timestamp column.

ALTER TABLE Orders
ADD RowVersion ROWVERSION

Used when multiple users update same order.


5️⃣ Distributed Lock (Redis / Cache)

In high-traffic systems.

Example:

Lock Key = Order_UserId_ProductId

If lock exists → reject request.

Tools:

  • Redis

  • Azure Cache

  • Distributed Lock library


6️⃣ Message Queue Deduplication (Microservices)

If using Kafka / SQS / RabbitMQ

Use:

  • MessageId

  • DeduplicationId

  • Exactly-once processing

Example AWS SQS:

MessageDeduplicationId

Prevents duplicate message processing.


7️⃣ Pessimistic Locking (SQL Server)

SELECT * 
FROM Orders WITH (UPDLOCK, HOLDLOCK)
WHERE OrderId = @OrderId

Locks row until transaction completes.


8️⃣ Transaction Handling

Use transaction scope to ensure atomic operation.

using(var transaction = await _db.Database.BeginTransactionAsync())
{
   // create order
   // update inventory

   await transaction.CommitAsync();
}

🔥 Real Enterprise Approach (Used in Amazon / Uber)

They combine:

1️⃣ Idempotency key
2️⃣ Unique DB constraint
3️⃣ Distributed lock (Redis)
4️⃣ Retry-safe APIs

This guarantees exactly one order.


🎯 Interview Answer (Short)

Duplicate orders can be prevented using Idempotency Keys, Unique Database Constraints, Distributed Locks, and UI click prevention.
The most reliable solution is Idempotent APIs where each request contains a unique key and the server processes it only once.


✅ If you want, I can also explain 7 real production scenarios where duplicate orders happen in microservices and how companies solve them (very useful for 40–60 LPA architecture interviews).

Sunday, 11 January 2026

Stored Procedure (SP) pagination for a data grid

Implementing Stored Procedure (SP) pagination for a data grid involves retrieving only a specific "page" of data from the database, rather than the entire dataset, which significantly improves performance and reduces network traffic. The modern and most efficient method in SQL Server (2012 and later) is using the OFFSET...FETCH NEXT clause. 
Stored Procedure Implementation (SQL Server)
The stored procedure needs input parameters for the page number, page size, and an ORDER BY clause (which is mandatory for OFFSET...FETCH). It may also include an output parameter for the total record count, which is useful for displaying navigation controls on the front end. 
sql
CREATE OR ALTER PROCEDURE [dbo].[uspGetPagedData]
    @PageNumber INT,
    @PageSize INT,
    @TotalRecords INT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    -- Get the total number of records
    SELECT @TotalRecords = COUNT(*) FROM [YourTableName];

    -- Retrieve the specific page of data
    SELECT *
    FROM [YourTableName]
    ORDER BY [YourSortColumn] ASC -- ORDER BY is required for OFFSET/FETCH
    OFFSET (@PageNumber - 1) * @PageSize ROWS
    FETCH NEXT @PageSize ROWS ONLY;
END
  • @PageNumber@PageSize: Input parameters to determine which data to retrieve.
  • @TotalRecords: An output parameter to return the total count of records in the table, enabling the UI to calculate the total number of pages.
  • OFFSET (@PageNumber - 1) * @PageSize ROWS: Skips the appropriate number of rows based on the current page and size.
  • FETCH NEXT @PageSize ROWS ONLY: Selects only the number of rows specified by the page size. 

Friday, 9 January 2026

Object Vs var Vs Dynamic Type in C#

 https://www.c-sharpcorner.com/UploadFile/ff2f08/object-vs-var-vs-dynamic-type-in-C-Sharp/


Introduction to object

The object class is the base class for all ohter classes; in other words all derived types are inherited from the object base type. We can assign values of any type to the object type variable (when the value type is converted to an object it is called "boxing" and when the variable type object is converted into any other value type is called "unboxing").

Example

object a = 10;
object b = "This is test string";
object c = a;

//Below is also possible with object type
object k = "jignesh";
k = 10;
C#

Introduction to var keyword

The var keyword was introduced in C# 3.0. It is an implicit type and the type is determined by the C# compiler. There is no performance penalty when using var. The C# compiler assigns types to the variable when it assigns the value.

Example

var a = 10; // it is same as int a = 10;
var b = "This is test string";
var c = b; // gives compilation error.

var words = new string[] { "apple", " banana", "peach", " grape" };
C#

It makes programs shorter and easier to read. In short the var keyword is an implicit way of defining data types. It is an indirect way of defining the variable type. The “var” keyword defines the data type statically (at compile time) and not at runtime.

The var keyword is very useful when.

  1. We have a long class name so that our code is not so readable. var makes it short and sweet.
  2. We use LINQ and anonymous types that help us reduce the code (reduce effort to create a new class).

Introduction to Dynamic Keyword

C# 4.0 introduced a new type called "Dynamic". Dynamic is a new static type that is not known until runtime. At compile time, an element with dynamic is assumed to support any operation so that we need not be worried about the object, whether it get the value from COM, the DOM, from reflection or anything else in the program. Errors are caught at runtime only. The dynamic type in C# uses the Dynamic Language Runtime (DLR) introduced as a new API in the .Net Framework 4.0. Type dynamic behaves like an object in most cases, but the expression of type dynamic is not checked by the compiler. The type's dynamic status is compiled into a variable type object that is dynamic at compile time, not at run time.

At compilation a dynamic is converted into a System.object and the compiler will emit the code for type safety during runtime. It suffers from boxing and unboxing because it is treated as a System.Object and also the application's performance will suffer siince the compiler emits the code for all the type safety.

Example

dynamic i = 10;
dynamic s = "Jignesh Trivedi";

string p = "This is test";
dynamic k = p;

dynamic other = 10; //assign int value so run time type is integer

other = "Jignesh"; // now runtime type of other varible become string.
C#

We can define a dynamic variable, property, field and parameter, return value, type constraint and so on.

// A dynamic field.
static dynamic field;

// A dynamic property.
dynamic name { get; set; }

// A dynamic return type and a dynamic parameter type.
public dynamic Method(dynamic parameter)
{
    dynamic local = "return string";
    int other = 0;

    if (parameter is string)
    {
        return local;
    }
    else
    {
        return other;
    }
}
C#
 ObjectVARDynamic
Introduce in FrameworkC# 1.0C#3.0C#4.0
Stored value typeIt can store any type of value because it is base class i.e. All types in .net framework are derived from object."It can store any type of value, but We must initialize ""var"" types at the time of declaration."It can store any type of value just like old VB language variables.
The compiler has information about the type?Compiler has very little information about the type.It is type safe. It means that the compiler has all information about the type so that there is no issue at run time.It is not type safe. It means that compiler doesn't have any information about the type of variable.
CastingNeed to cast object variable to original type when use it.No need to cast because the compiler has all information about the type.Casting is not required, but we need to know the properties and methods related to stored type because intelligence is not available for dynamic type.
Intellisense support?NoYesNo
Cause the problem at run time?Yes. It throws runtime exception when compiler is not able to convert values from stored value type to required type.No, because type is already known by compiler.Yes. It throws runtime exception When properties or method name are mismatched from original.
UsefulnessIt is very useful when we don't have more information about the type.It is useful when we don't know the actual type.It is very useful when we are using dynamic language for coding or use COM component in our code.
Does it pass to a method or create typed properties?Yes. It can be passed as method parameter and method also can return object type."No, we cannot declare a method parameter or return type as ""VAR""""Yes, we can declare a method parameter or
return type as ""VAR"""

Recent Post

how to control duplicate order