Wednesday, 20 August 2025

IQ


 1. Latest .NET Core version

 As of 2025, the latest is .NET 9 (LTS).

 .NET Core merged into .NET 5+ (now just “.NET”).

 Current LTS: .NET 8 (released Nov 2023).

 Current STS: .NET 9 (released Nov 2024).

---

 2. Your approach in CQRS pattern

 Separate read & write models:

   Commands → handle writes (insert, update, delete).

   Queries → handle reads (optimized for performance).

 Approach:

  1. Client sends command → goes through Command Handler.

  2. Event created → updates read DB.

  3. Queries directly hit read DB (fast).

 Benefits: Scalability, separation of concerns, optimized queries.


---

 3. How microservices communicate

 Synchronous (direct call): REST APIs, gRPC → when real-time response needed.

 Asynchronous (decoupled): RabbitMQ, Kafka, Azure Service Bus → event-driven, loose coupling.


---

 4. How to populate data from two tables using microservice

 Options:

  1. If both tables belong to same microservice DB → write a join query inside that microservice.

  2. If tables belong to two different microservices →


      Use API Composition (Aggregator calls both services & merges response).

      Or use CQRS + Event Sourcing (each service publishes data → materialized view built for combined query).

---


 5. Request flow in microservices

1. Client → API Gateway.

2. Gateway → routes request to proper microservice.

3. Microservice processes (may call DB or other microservices).

4. Response goes back via API Gateway → Client.

5. If async, service publishes event to message broker → another service consumes it.

---

 6. Abstract class – when it is used

 Abstract class = base class that cannot be instantiated, may contain abstract (unimplemented) and concrete (implemented) methods.

 Used when:

   You want common behavior in base class but also enforce derived class implementation.

   Example: `Shape` class → `Draw()` abstract, but `Area()` default implemented.

---

 7. If two tables updation in microservice

 If both tables in same microservice DB → use transaction (ACID).

 If two different microservices DBs → use Saga Pattern for distributed transaction.

   Or event-driven update with eventual consistency.

---

 8. Web API Gateway techniques

 Reverse Proxy Routing → routes client requests to right microservice.

 Aggregation Pattern → combine multiple service responses into one.

 Security → JWT validation, authentication, authorization at gateway.

 Resilience → Circuit breaker, retries, caching, throttling.

 Examples: Ocelot (for .NET Core), Kong, NGINX, Azure API Gateway.


---

 9. Authentication in microservices

 Common approach:

   Use Identity Provider (IdP) → (e.g., IdentityServer4, Keycloak, Azure AD, Auth0).

   Issue JWT token after login.

   API Gateway validates JWT before forwarding request.

   Each microservice validates claims/roles inside JWT.

---

 10. How to configure Authentication

 In .NET Core:

   Use `AddAuthentication().AddJwtBearer()` in `Program.cs`.

   Configure authority (IdP) & signing key.

   Decorate controllers with `[Authorize]`.

 Gateway (Ocelot/YARP) configured to check `Authorization` header.

---

 11. I have 4 microservices, but how the user communicates with one service

 User never calls microservice directly.

 User → API Gateway → Gateway routes to respective microservice.

 API Gateway hides internal service details.

 Example:

   User Service, Order Service, Product Service, Payment Service.

   User calls Gateway → /orders → internally goes to Order microservice.

-------------------------------------------------------------------------------------------------------------------

1. Main purpose of Terraform

 Infrastructure as Code (IaC) tool.

 Used to provision and manage infrastructure (cloud/on-prem) in a declarative way.

 Key purposes:

   Automate infra creation (servers, DB, VPCs, etc.).

   Maintain infra consistency across environments.

   Version control infra (works like Git for infra).

   Supports multi-cloud (AWS, Azure, GCP).

---

 2. Issues faced in CI/CD pipeline

Common issues:

 Build failures due to dependency/version mismatch.

 Slow pipelines (long build/test times).

 Flaky tests breaking builds intermittently.

 Secrets management (credentials leaking).

 Environment drift (works in dev but not in prod).

 Rollback challenges when deployment fails.

 Merge conflicts with multiple developers pushing at once.

---

 3. How you will maintain logs

 Centralized logging system:

   Use CloudWatch (AWS), Application Insights (Azure), or ELK/EFK stack.

 Implement structured logging (JSON format).

 Log levels: Debug, Info, Warn, Error, Fatal.

 Log rotation/retention policies to avoid storage issues.

 Use correlation IDs/trace IDs for distributed microservices.

---

 4. What is RDS

 Relational Database Service (AWS) – managed database service.

 Supports MySQL, PostgreSQL, Oracle, SQL Server, MariaDB, Aurora.

 Handles patching, backups, replication, failover automatically.

---

 5. Read Replica vs Write Replica

 Write Replica (Primary DB):

   Handles both read & write operations.

   Source of truth.

 Read Replica:

   Async copy of primary DB.

   Used for read-heavy workloads to reduce load on primary.

   No writes allowed.

---

 6. Disaster recovery same AZ

 Bad practice – if AZ fails, everything goes down.

 Disaster Recovery (DR) should be in multi-AZ or multi-region.

 Within same AZ → only works for instance-level failure, not for AZ-wide outages.

---

 7. Difference between Availability Zone (AZ) and Region

 Region = Geographical area (e.g., us-east-1, ap-south-1).

 AZ = Isolated datacenters inside a region (e.g., us-east-1a, us-east-1b).

 Each region has multiple AZs for high availability.

---

 8. How AZ works

 Each AZ = independent power, networking, cooling.

 AZs in a region are connected with low-latency links.

 Deploying across AZs → fault tolerance & high availability.

---

 9. Authentication vs Authorization

 Authentication = verifying who you are (identity check, login).

 Authorization = verifying what you can do (permissions, access control).

 Example:

   Authentication = Login with username/password.

   Authorization = Access admin dashboard only if you’re an admin.

---

 10. Difference between Concurrency and Parallelism

 Concurrency = dealing with multiple tasks at the same time (not necessarily simultaneous). (Context switching).

 Parallelism = executing multiple tasks exactly at the same time (multi-core processing).

 Example:

   Concurrency = CPU switches between downloading file & watching video.

   Parallelism = Two CPU cores → one downloads file, other plays video.

---

 11. Unit Testing

 Testing smallest unit of code (method/class).

 Ensures function works as expected in isolation.

 Benefits: Catch bugs early, regression prevention, confidence in code changes.

 In C#: NUnit, xUnit, MSTest.

---

 12. CQRS (Command Query Responsibility Segregation) Workflow

 Command (Write model):

   Handles changes → Create, Update, Delete.

   Goes through domain/business logic.

 Query (Read model):

   Handles read-only requests.

   Uses optimized read DB (e.g., denormalized data).

 Workflow:

  1. Client sends command (e.g., "Place Order").

  2. Command handler updates DB (write model).

  3. Event generated → updates read model.

  4. Client queries read model for fast response.

 Benefits: Scalability, performance, separation of concerns.

---

 13. Design Patterns in Microservices

Commonly used:

 API Gateway Pattern – single entry point for all microservices.

 Database per service Pattern – each microservice owns its DB.

 Saga Pattern – manage distributed transactions.

 CQRS Pattern – separate read/write models.

 Event Sourcing – capture all changes as events.

 Strangler Pattern – migrate monolith to microservices gradually.

 Circuit Breaker – handle failures gracefully.

---

 14. Terraform

 Already covered: Infra as Code tool.

 Uses .tf files with HCL (HashiCorp Configuration Language).

 Features:

   Plan → preview infra changes.

   Apply → provision infra.

   State file → tracks real infra state.

   Modules → reusable infra components.

 Benefits: Consistency, automation, version-controlled infra.


-------------------------------------


 JWT token

 What: Self-contained token with signed claims (e.g., `sub`, `exp`, `aud`).

 Why: Stateless auth between client ↔ API.

 Validate: Verify signature, issuer, audience, expiry.

 Expiry time (JWT `exp`)

 Claim: Unix time when token becomes invalid.

 Typical: Access token 5–30 min; Refresh token days–weeks.

 Reason: Limit blast radius if stolen.

 Refresh token — purpose

 Get a new access token without re-login.

 Long-lived, stored securely (HTTP-only cookie/secure store).

 Use rotation + revocation list.

---

 Delegate in C\

 Type-safe function pointer (method reference).

csharp

public delegate int Op(int x, int y);

int Add(int a,int b)=>a+b;

Op op = Add; var r = op(2,3);

 Multicast delegate

 One delegate invokes multiple methods (invocation list). Return value is last method’s return.


csharp

Action a = () => Console.Write("A");

a += () => Console.Write("B");

a(); // prints "AB"

---

 Unique elements with collections (C)

 Fastest: `HashSet<T>` (O(1) average add/lookup).

 LINQ: `var uniques = items.Distinct();`

 Count uniques: `new HashSet<T>(items).Count`.

---

 Binary search vs Linear search

 Linear: O(n); works on unsorted data; simple.

 Binary: O(log n); requires sorted data & random access (array).

---

 Which data structure are you using? (how to answer)

 Lookups → `Dictionary<K,V>` / `HashSet<T>`

 Order + fast min/max → `SortedSet<T>` / `PriorityQueue<T>`

 FIFO/LIFO → `Queue<T>` / `Stack<T>`

 Indexed sequence with frequent inserts at end → `List<T>`

 Contiguous & fixed size → array

 Streaming top-K → heap/`PriorityQueue<T>`

---

 Code-first approach (EF Core)

 Define C entity classes → generate DB via migrations.

dotnet ef migrations add Init

dotnet ef database update

 Pros: versioned schema, migrations in code.

 Watch for: explicit configurations (`Fluent API`) for keys/relations.

---

 NuGet package for JWT (ASP.NET Core)

 `Microsoft.AspNetCore.Authentication.JwtBearer` (middleware)

 `System.IdentityModel.Tokens.Jwt` (token handling)

---

 Protect API from (common threats & how)

 Unauthorized access → JWT/OAuth2, `[Authorize]`, scopes/roles.

 Transport attacks → Enforce HTTPS.

 Injection (SQL/XSS) → parameterized queries, input validation.

 CSRF (if using cookies) → anti-forgery tokens, SameSite, HTTP-only.

 CORS → allow only trusted origins.

 Secrets → managed stores (Key Vault/Secrets Manager), rotate keys.

 Rate abuse → throttling, API Gateway/WAF.

 Error info leak → centralized error handling, generic messages.

To protect an API, I ensure proper **authentication** (commonly JWT or OAuth2), followed by **authorization** using roles or scopes. I enforce **HTTPS** to secure communication and use **rate limiting** to prevent abuse. I also validate and sanitize all inputs to prevent injection attacks. On top of that, I implement proper **logging, monitoring, and global error handling** to detect and respond to issues. For enterprise setups, I would place the API behind an **API Gateway or WAF** to centralize authentication, throttling, and request validation.

---

 Prevent API from DDoS

 Rate limit / throttling (per IP/key).

 WAF/CDN (AWS WAF, CloudFront; Azure WAF/Front Door).

 Bot detection / CAPTCHA (for public endpoints).

 Autoscale + circuit breaker + timeouts.

 Cache hot GETs; use idempotency keys on writes.

 Network rules: IP allow-lists for internal APIs.

---

 Indexes (RDBMS)

 Clustered: defines row order on disk (table data = index). One per table (SQL Server).

 Nonclustered: separate structure with key + row locator; many allowed.

 Covering index: includes all needed columns → fewer lookups.

 Trade-off: more indexes speed reads but slow writes & increase storage.


How many indexes (SQL Server)


 Clustered: 1.

 Nonclustered: up to \~999 possible; keep it lean (often 3–10 well-chosen).

---

 Performance SQL query (quick hits)

 Write SARGable predicates (`WHERE Col = @p`, avoid functions on columns).

 Add proper indexes (seek > scan); use covering indexes for hot queries.

 Avoid `SELECT `; project only needed columns.

 Check execution plans; fix key lookups, scans, spills.

 Keep statistics up-to-date; consider filtered/ composite indexes.

 Batch operations; avoid RBAR; prefer set-based logic.

 Normalize write paths; denormalize or materialize views for reads if needed.

---

 How to communicate microservices

 Synchronous: REST (JSON), gRPC (binary, fast). Use for request/response.

 Asynchronous: message broker (RabbitMQ, Kafka, SQS/SNS, Service Bus) for events, decoupling, retries.

 Patterns: Saga, Outbox, Idempotency, Correlation IDs, Retries + backoff, Circuit Breaker.

---

 Circuit Breaker

 Pattern to stop calling an unhealthy dependency:

   Closed (normal) → failures trip to Open (fast-fail) → after cooldown Half-Open (probe).

 .NET: Polly (or .NET 8 Resilience).

 Benefits: protects resources, improves latency under failure.


---

 S3 bucket in AWS (essentials)

 Object storage (files as objects in buckets).

 Key features: versioning, lifecycle rules (transition to Glacier/expiry), encryption (SSE-S3/KMS), policies & ACLs, presigned URLs, static website hosting, replication.

 Security: block public access (by default), bucket policies/IAM, VPC endpoints.

 Consistency: strong read-after-write for new objects/overwrites.


---

 Tiny .NET JWT setup (bonus)

csharp

// Program.cs

builder.Services.AddAuthentication("Bearer")

  .AddJwtBearer("Bearer", o => {

    o.TokenValidationParameters = new TokenValidationParameters {

      ValidateIssuerSigningKey = true,

      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("<secret>")),

      ValidateIssuer = true, ValidIssuer = "https://issuer",

      ValidateAudience = true, ValidAudience = "api",

      ValidateLifetime = true, ClockSkew = TimeSpan.Zero

    };

  });

builder.Services.AddAuthorization();

var app = builder.Build();

app.UseAuthentication();

app.UseAuthorization();

---

What is DDoS?

DDoS = Distributed Denial of Service.

It’s a type of cyber attack where many compromised systems (often bots in a botnet) flood a target (like a server, API, or website) with huge amounts of requests.

---

 Example

* Normal request rate: 100 req/sec

* Attacker launches botnet: 100,000 req/sec from thousands of machines.

* Your server cannot handle it → crashes or becomes unresponsive.

---

 Types of DDoS

1. Volumetric Attacks – Flood network with traffic (UDP floods, ICMP floods).

2. Protocol Attacks – Exploit protocol weaknesses (SYN flood, Ping of Death).

3. Application Layer Attacks – Target APIs/web apps (HTTP floods, slow requests).

---

 How to Prevent/Mitigate

* Rate limiting & throttling on APIs.

* CDN / Load balancer (Cloudflare, AWS CloudFront, Azure Front Door).

* WAF (Web Application Firewall) → blocks malicious traffic.

* DDoS protection services (AWS Shield, Azure DDoS Protection).

* Scaling out (auto-scaling servers, Kubernetes).

---

 “A DDoS (Distributed Denial of Service) attack happens when multiple machines flood an API or server with traffic, making it unavailable to real users. To prevent it, we use rate limiting, caching, API gateways, WAFs, CDNs, and cloud DDoS protection services like AWS Shield or Azure DDoS Protection.”


No comments:

Post a Comment