Saturday, August 30, 2025

How to Implement MicroServices in .Net Core Application- Point-to-point to explanation

 

1) Service boundaries & contracts

  • One business capability per service (e.g., Orders, Payments, Catalog). Each owns its own database.
  • API surface: REST (JSON) or gRPC for synchronous calls; events (Kafka/RabbitMQ/Azure Service Bus) for async integration.
  • Version your APIs (e.g., /v1), keep backward compatible changes, use OpenAPI/Swagger and contract tests (Pact).

2) Resilience patterns (timeouts, retries, circuit breaker, bulkhead)

Use HttpClientFactory + Polly on every outbound call:

builder.Services.AddHttpClient("CatalogClient", c =>

{

    c.BaseAddress = new Uri(config["CatalogUrl"]);

    c.Timeout = TimeSpan.FromSeconds(3);

})

.AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(

    retryCount: 3,

    sleepDurationProvider: attempt => TimeSpan.FromMilliseconds(200 * Math.Pow(2, attempt)), // expo backoff

    onRetry: (outcome, ts, attempt, ctx) =>

        logger.LogWarning(outcome.Exception, "Retry {Attempt}", attempt)))

.AddTransientHttpErrorPolicy(p => p.CircuitBreakerAsync(

    handledEventsAllowedBeforeBreaking: 5,

    durationOfBreak: TimeSpan.FromSeconds(30)))

.AddPolicyHandler(Policy.BulkheadAsync<HttpResponseMessage>(maxParallelization: 50, maxQueuingActions: 100));

Rules of thumb

  • Always set timeouts on I/O.
  • Prefer idempotent operations; send Idempotency-Key headers for POSTs where possible.
  • Use cancellation tokens end-to-end.

3) Circuit breaker semantics

  • Trip when a dependency is unhealthy; fail fast and return a cached/partial response or friendly error.
  • Expose breaker state via metrics and health checks (see §5).

4) Data & database handling (consistency without distributed transactions)

  • Database per service (EF Core or Dapper). No cross-service joins.
  • Propagate data between services using domain events—not shared tables.
  • Ensure atomicity with the Outbox pattern:
    1. Write your entity and an OutboxMessage row in the same DB transaction.
    2. A background Outbox Publisher reads unpublished rows and emits them to the broker, then marks them sent.

// Inside your OrderService command handler

await using var tx = db.Database.BeginTransactionAsync();

db.Orders.Add(order);

db.Outbox.Add(new OutboxMessage {

    Type = "OrderPlaced",

    Payload = JsonSerializer.Serialize(new { order.Id, order.Total, order.CustomerId }),

    OccurredOn = DateTimeOffset.UtcNow

});

await db.SaveChangesAsync();

await tx.CommitAsync();

// BackgroundService publisher

protected override async Task ExecuteAsync(CancellationToken ct)

{

    while (!ct.IsCancellationRequested)

    {

        var messages = await db.Outbox

            .Where(m => m.SentOn == null)

            .OrderBy(m => m.OccurredOn)

            .Take(100).ToListAsync(ct);

 

        foreach (var msg in messages)

        {

            await broker.PublishAsync(msg.Type, msg.Payload, ct);

            msg.SentOn = DateTimeOffset.UtcNow;

        }

        await db.SaveChangesAsync(ct);

        await Task.Delay(TimeSpan.FromSeconds(1), ct);

    }

}

  • Updating “relative/related” databases: consume those events in other services to update local read models (CQRS). Use Sagas (orchestration or choreography) for multi-step processes (e.g., Order → Reserve Inventory → Process Payment → Arrange Shipping), with timeouts + compensation.

5) Health checks, readiness, and monitoring

Add liveness (process alive) and readiness (deps OK) endpoints:

builder.Services.AddHealthChecks()

    .AddSqlServer(config.GetConnectionString("OrdersDb"))

    .AddRabbitMQ(config["RabbitMq:Connection"])

    .AddUrlGroup(new Uri(config["CatalogUrl"] + "/health"), name: "catalog");

 

app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false });

app.MapHealthChecks("/health/ready", new HealthCheckOptions {

    Predicate = _ => true,

    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse

});

  • Kubernetes/Containers probe /health/live and gate traffic on /health/ready.
  • Add self-diagnostics (thread pool starvation, GC info) via EventCounters exported by OpenTelemetry.

6) Observability (logs, traces, metrics)

Unified, structured telemetry makes bugs easy to fix.

OpenTelemetry (logs + traces + metrics) → backends like Grafana Tempo/Prometheus/Loki, Jaeger, Elastic, or Azure Application Insights.

builder.Services.AddOpenTelemetry()

 .WithTracing(t => t

     .AddAspNetCoreInstrumentation()

     .AddHttpClientInstrumentation()

     .AddSqlClientInstrumentation()

     .AddSource("OrderService")

     .AddOtlpExporter()) // or Azure Monitor exporter

 .WithMetrics(m => m

     .AddAspNetCoreInstrumentation()

     .AddRuntimeInstrumentation()

     .AddHttpClientInstrumentation()

     .AddPrometheusExporter());

 

app.MapPrometheusScrapingEndpoint(); // /metrics

Structured logging (e.g., Serilog → console/JSON + sink of choice):

Log.Logger = new LoggerConfiguration()

    .Enrich.FromLogContext()

    .Enrich.WithCorrelationId()

    .WriteTo.Console(new JsonFormatter())

    .WriteTo.Seq(config["SeqUrl"]) // or Elastic/Azure

    .CreateLogger();

 

builder.Host.UseSerilog();

  • Include CorrelationId/TraceId in every log; propagate with middleware:

app.Use(async (ctx, next) =>

{

    var cid = ctx.Request.Headers["X-Correlation-ID"].FirstOrDefault() ?? Guid.NewGuid().ToString();

    ctx.Items["CorrelationId"] = cid;

    ctx.Response.Headers["X-Correlation-ID"] = cid;

    using (LogContext.PushProperty("CorrelationId", cid))

        await next();

});

  • Emit domain events and key business metrics (orders placed, failures, latencies, queue depth).

7) API gateway / proxy servers

  • Use a Gateway for routing, TLS, auth/ratelimiting, request shaping:
    • YARP (in-process .NET reverse proxy) or Ocelot; at the edge you can also use NGINX/Envoy.
  • Centralize AuthN/Z (OAuth2/OIDC via Azure AD, Auth0, or Duende IdentityServer), rate limits, request/response size limits, CORS, and header normalization at the gateway.
  • Prefer service discovery (K8s DNS) and mTLS in cluster; consider a service mesh (Istio/Linkerd) for uniform retries/mtls/traffic shifting and better telemetry without code changes.

8) Security & configuration

  • Never share DBs across services. Grant least privilege per service.
  • Secrets via Azure Key Vault / K8s secrets; bind with IOptions<T> and validate on startup.
  • Enforce TLS everywhere, JWT validation, rotating keys, and input validation (FluentValidation).

9) Deployment & runtime

  • Containerize each service (Docker), build once, promote the same image through Dev → QA → Prod.
  • Orchestrate with Kubernetes (AKS) or Azure App Services for simpler cases.
  • Blue/Green or Canary deployments; mesh/gateway can split traffic gradually.
  • Horizontal scaling via HPA (CPU/RPS/latency). Keep services stateless; externalize state (DB/cache).
  • Caching: local memory for tiny TTLs, Redis for shared cache; always set cache keys + expirations.

10) CI/CD and quality gates

  • GitHub Actions / Azure DevOps Pipelines:
    • Build → unit/integration/contract tests → SCA & SAST → container scan → publish image → deploy via Helm/Bicep/Terraform.
    • Block merges without green tests and security checks.
  • Spin ephemeral test environments per PR when feasible.

11) Diagnostics & “easy bug fixing”

  • Global exception handler → consistent error envelopes with traceId:

app.UseExceptionHandler(builder =>

{

    builder.Run(async ctx =>

    {

        var traceId = Activity.Current?.Id ?? ctx.TraceIdentifier;

        var problem = new { traceId, message = "Unexpected error." };

        ctx.Response.StatusCode = 500;

        await ctx.Response.WriteAsJsonAsync(problem);

    });

});

  • Feature flags (Azure App Configuration) for safe rollouts; dark-launch code paths.
  • Replayable messages (don’t auto-ack until processed). Keep dead-letter queues and dashboards.
  • Synthetic checks (probes that place a tiny test order in lower envs and alert on end-to-end failure).

12) Database migrations & uptime

  • Apply EF Core migrations at startup (carefully) or via migration jobs;
    • Prefer expand-and-contract: add new columns/tables (expand), release code that writes both, backfill, then remove old fields (contract).
  • For read models, permit rebuild from event streams or upstream APIs if corrupted.

13) Monitoring & alerts you’ll actually use

  • Golden signals per service: Latency, Traffic, Errors, Saturation.
  • Alert on SLIs/SLOs (e.g., p95 < 300ms, error rate < 1%), queue lag, breaker open rate, DB CPU, connection pool exhaustion.
  • Route alerts to Teams/Slack with runbooks linked (how to diagnose/rollback).

14) Local/dev ergonomics

  • Docker-compose for local broker + DB + dependencies.
  • Seed data + test fixtures; make services start with sensible defaults.
  • Makefile/PS scripts for common tasks; one-command bootstrap.

Minimal reference architecture (quick checklist)

  • ASP.NET Core services (+ gRPC if needed)
  • HttpClientFactory + Polly (timeouts/retries/circuit breaker/bulkhead)
  • Outbox + BackgroundPublisher; events over Kafka/RabbitMQ/Azure Service Bus
  • DB per service (EF Core/Dapper) + migrations (expand/contract)
  • OpenTelemetry (traces/metrics/logs) → Prometheus/Grafana/Tempo or App Insights
  • Serilog structured logging + correlation IDs
  • Health checks: /health/live, /health/ready
  • API Gateway: YARP/Ocelot; edge NGINX/Envoy; OAuth2/OIDC
  • Containerized; AKS/App Service; blue/green or canary
  • CI/CD with tests, scans, infrastructure as code
  • Feature flags; DLQs; synthetic probes; runbooks


 

Tuesday, November 21, 2023

Joint Declaration Form -EPFO - For correction of details as per Aadhaar Card.

 If your EPFO details is not matching with Aadhaar card then you unable to login https://passbook.epfindia.gov.in/MemberPassBook/login if you want correct the details as per Aadhaar Card , we need to submit photo copy of Aadhaar card, PAN, DOB proof and letterhead of your

 organization with joint document form details.

All the documents which mentioned should have have attested with organization authority.

need to submit these documents along with joint document form provided by EPFO office.

once you submit these documents you will get corrected your details within the month.

Note : if you have more than one organization PF accounts, need to submit for same documents for two organizations.

JOINT DECLARTION FORM -Format

Image later Content 




(On letter head of the Establishment)

Joint Declaration Form

 

I ____________________________having UAN ______________________________________

PF account __________________________ and Aadhaar ______________________________

is/was the employee of establishment M/S. _________________________________________

The personal details furnished to EPFO earlier were found to be incorrect /bank, and therefore

request for change/updation in the member profile as follows.

 

S.NO.

Details/particulars

Incorrect details

Correct details

1

Aadhaar

 

 

2

Name

 

 

3

DOB

 

 

4

Gender

 

 

5

Father’s/Mother’s Name

 

 

6

Relationship

 

 

7

DOJ

 

 

8

DOL

 

 

9

Reason of leaving

 

 

10

Marital Status

 

 

11

Nationality

 

 

 

I______________________________S/o________________________authorized signatory of

the  establishment,  have  verified  the  request,  document  attached  and  the  records  of  the establishment   and    certify   that    the    facts   mentioned   above   are   correct.    I   am   also enclosing _____________________________,  ___________________________________and

________________________ (documents of Establishment)   in  support  of   the request ofthe

employee mentioned above.

 

We________________________________(Employee) and______________________________

(Authorized Signatory) hereby declare we have not concealed any facts and the above-mentioned facts are correct. We also indemnify that incase of wrong payment/over payment/under payment

Because of the above furnished information shall be jointly held responsible.

 

 

 

 

Authorized Signatory                                                 Name & Signature of the member




Wednesday, August 29, 2018

How to go Moula Ali -Hyderabad, Telangana.

All Govt Jobs Examinations Conducting in Moula Ali Examination center Near Coca cola Company in Hyderabad.
here is the information to reach Examination centre.

Train: Three to Four Railway stations are there to reach Moula Ali.

1. Secunderabad Jn- After getting down in Secunderabad Jn. Have to travel using RTC buses to reach Moula Ali(Bus No-16,17)[Blue C cafe Opp Busstop]
Private transportation also available (auto fares are not more than 200).you can use Metro rail also to reach Moula Ali(Secunderabad-Taranaka) from Tarnaka have take autos or buses to reach Moula ali.

2.Moula Ali Railway Station: Have to Use Travel Apps(like ola,Uber etc),No RTC buses. Autos available in between 6 Am to 6 Pm, very less chance to get autos in the nights, means after 7 pm.
Note: Food and Hotels are not available at Moula Ali railway station. Have to walk(2kms) or auto to get food.
Lodges are available in Ecil and Tarnaka.
3.Kachiguda Railway Station: RTC buses available from near Kachiguda railway station, Have to walk less than half a kilometer to get buses.

4.Malkjgiri Railway Station: Auto s available from Malkajgiri for buses have to walk less than half a kilometer to get buses.

Bus : MGBS,JBS(RTC bus stops),IF private travels have to get down Ecil or Tarnaka from there you can get buses autos to reach moula ali examination centre.

If you want to stay in the nights Ecil or Tarnaka is best places.

Wednesday, December 13, 2017

IS Ram Sethu is True ?






Monday, December 11, 2017

How to find duplicate records from sql server Table and Delete

How to find the duplicate record ?

Finding duplicate record from table using CTE.

WITH CTE
AS
(SELECT NAME,EMP_ID,ROW_NUMBER()
OVER(PARTITION BY NAME ORDER BY NAME)
AS NAMEDUP FROM EMPLOYEE)
SELECT * FROM CTE WHERE NAMEDUP > 1 ORDER BY NAME

Using Having Count

SELECT NAME,COUNT(NAME)FROM EMPLOYEE
GROUP BY NAME HAVING COUNT(*)>1

Using group by

SELECT NAME,COUNT(NAME) AS CNT
FROM EMPLOYEE
GROUP BY NAME

Deleting duplicate records from the table.

WITH CTE
AS
(SELECT NAME,EMP_ID,ROW_NUMBER()
OVER(PARTITION BY NAME ORDER BY NAME)
AS NAMEDUP FROM EMPLOYEE)
DELETE FROM CTE WHERE NAMEDUP > 1



Wednesday, December 6, 2017

How to set Sql Server Mode In IIS in ASP.NET ?

1.We need not to create a  new database We have a tool called aspnet_regsql.exe tool (Aspnet registersql).
This tool is present in c:\windows\Microsoft.net\framework64\version.
2.In the Run command window prompt we have to run below mentioned commands
A.In that mentionpath where the tool exists,Toolname -s Sqlservername -E(Means windowauthentication) -ssadd(Add support for SQL serve sessionmode -sstype p(MeansSession variables will store in ASP state sql server database)
3.Need to set mode to SQLserver
<sessionstate mode="SqlServer" sqlconnectionstring="datasource=.; userid="username" pwd="p***"/>




What are the Event Handlers that can be included in the Global.asax file ?

There total 5 events in global.aspx file
1. Application_start
 --- When ever first instance of HTTPApplication class created.
2.Application_Error:
-- When ever unhandled exception occurs in the Application
3.Application_End
--- When ever last instance HTTPApplication class destryoyed.
4.Session_Start :
 -- user visits the application.
5. Session_End :
   --- When the session state is set to inproc then this event gets fired.

Thursday, November 30, 2017

how to find special characters in database tables in db2

Have to use TRANSLATE funtion to find the special characters data in db2.


ex :

SELECT COL1,COL2
FROM TABLENAME WHERE LENGTH(TRIM(TRANSLATE(COL3,'`!@#$%^&*()_-+=|\}]{[":;?/<,>.',' '))) IS NULL


SELECT COL1,COL2,COL3,TRIM(TRANSLATE(COL3,'`!@#$%^&*()_-+=|\}]{[":;?/<,>.',' '))
FROM TABLENAME

Thursday, October 26, 2017

How to know built in functions in Python

How to know the built in functions in Python ?

To know built in functions in Python type dir(__builtins__) press enter you will get all built in functions.

if you want to know how the functions works use Help to know the functionality
like
help(pow) it will display the functionality of particular function




Thursday, July 27, 2017

Secrets About Sabarimala in telugu

Secrets About Sabarimala in Telugu watch the video







Sunday, December 4, 2016

Do's and Don'ts in Swamy ayyappa deeksha

To visit divine place sabarimala devotees need to take deeksha for 41(mandalam) days.



Here are the do's and don'ts of while in ayyappa deeksha.


1.Need to wear ayyappa mala rudraksha mala with ayyappa pendent.
2.To wear this mala need to visit any temple , this wearing is done by your mother or guruswamy(who completes 18 times of mala dharanam).
3.After maladharanam your deeksha starts ,through out deeksha need to fallow below mentioned points.
4.Everyday early morning have to take bath with normal water(not hot water in case if you are suffering with any sinus problems)
          4 am  Devatha snanam
 5 am  Manush snanam
 6 am  Rakshasa snanam.
 Means need to take bath before sun rise.
5.After bath have to do Pooja in home or in temple.
6.In home need to place ayyappa along with ganesh and kumara swamy(with suggestions of poojari or guru swamy).
7.Need to clean every day morning and evening your home or pooja room(where you placed ayyappa).
8.Pooja with 108 astothras ganesh,subramanyam and ayyappa.(You can other gods also with interest but ends with ayyappa.)
9.Throughout deeksha need to wear black dress.
10.wearing shoe or chappal not allowed.
11.Self made food or fruits are preferable in these mandalam days.
12.no smoking,drinking and non veg.
13.Bramhacharyam need fallow.
14.No movies and no entertainment.
15.Sleep on floor or mat.(bed not allowed).
16.Call women(wife Also) as 'Matha' and men as 'Swamy'.




17.No shaving and hair cut.
18.Best avoid using social media like facebook,twitter,whats app..etc.
19.Control all type feelings(like anger....).
20.Attend bajanas poojas regularly.
21. In deeksha need to call fellow swamys for lunch or dinner(1 also enough.as per your budget).
22.Chant ayyppa mantras.
23.For working men some are not possible but try as much as you can.

Swamiye saranam ayypppa.

Wednesday, November 23, 2016

Sabaarimala temple name changed





Sabarimala temple name changed to Sabarimala Sree Ayyappaswamy Temple.
Travancore Board decide this to change the tample name from sabarimala to sabarimala sree ayyappaswamy temple.

Thursday, November 10, 2016

Old notes still valid upto tomorrow midnight


You can allowed to pay utility bills,
Like power bill,water bill,land tax and other municipal bills by using old 500 and 1000 rs.
Whole India it is applicable to use old 500 1000 notes to pay the bills.
KTR Specially requested to central government.

Saturday, October 1, 2016

Rare October after 863 years

Very rare the month of October 2016. Coming after 8 centuries. Kakatiya contained month period will repeat now.
Full moon and New Moon in the same month, 3 festivals, Exactly 863 years ago this month that 1153 was the year.
5 Sundays
5 Mondays,
5 Saturdays.
Bathukamma,
Dussehra,
Peers ,
Diwali festivals. It has all of the same month. Usually do not come in a single month.



15 days  Dasara holidays.
IT employees to include 12 days holiday.
October highlights:
Sundays: 2, 9, 16, 23, 30
Mondays: 3, 10, 17, 24, 31
Saturdays: 1, 8, 15, 22, 29
Festivals: Bathukamma samburalu, Dussehra (11), peers and festival (12), Diwali (30)
Full Moon (16) and new moon (30)

Rare 863-year-old after October

Wednesday, August 31, 2016

That is PV sindhu and Badminton


Over 6 crores people watched PV Sindhu Badminton final match in India, Its a all time record TV channels watching one channel in at time, that to be Indians watching other than Cricket.
It is proved that PV Sindhu slowly turned Indians interest from Cricket to Badminton, Previously no Cricket match got these many viewers at time.

Slowly Indians changing their cricket fever to Badminton fever.

Blog Archive

Don't Copy

Protected by Copyscape Online Plagiarism Checker

Pages