wasAsked.
Ravindra Wadile's profile

Ravindra Wadile

·

0 followers · 0 following

Published questions

    Community answers

    Angular State Management – Input/Output, Services, NgRx, and Signals

    # Angular State Management – Input/Output, Services, NgRx, and Signals Angular provides multiple ways to manage state. The right approach depends on the **scope and complexity of the state**. ### 1. `@Input()` / `@Output()` Best for **parent-child component communication**. ```typescript // Parent <app-user [user]="user" (userChanged)="onUserChanged($event)" /> ``` ```typescript // Child @Input() user!: User; @Output() userChanged = new EventEmitter<User>(); updateUser(user: User) { this.userChanged.emit(user); } ``` **Use when:** * State belongs to a component. * Communication is mainly between parent and child. * The component hierarchy is simple. **Limitation:** Passing data through multiple component levels can become cumbersome, commonly called **prop drilling**. --- ### 2. Services A service is useful for **sharing state between unrelated components**. ```typescript @Injectable({ providedIn: 'root' }) export class CartService { private items: Product[] = []; addItem(item: Product) { this.items.push(item); } getItems() { return this.items; } } ``` Components inject the same singleton service and can access shared state. **Use when:** * State is shared across multiple components. * The state logic is relatively simple. * You don't need the full NgRx architecture. For more reactive state, services can use **RxJS `BehaviorSubject`/`Observable`** or Angular Signals. --- ### 3. NgRx NgRx is generally used for **large and complex application state**. Typical flow: ```text Component ↓ Dispatch Action ↓ Reducer / Effect ↓ Store ↓ Selector ↓ Component ``` Example: ```typescript store.dispatch(loadUsers()); ``` Reducer: ```typescript on(loadUsersSuccess, (state, { users }) => ({ ...state, users, loading: false })) ``` Component: ```typescript users$ = this.store.select(selectUsers); ``` **Advantages:** * Centralized state. * Predictable state transitions. * Excellent debugging with Redux DevTools. * Clear separation of actions, reducers, selectors, and effects. * Good for complex workflows and large teams. **Disadvantages:** * More boilerplate. * More concepts to learn. * Can be overkill for small applications. --- ### 4. Angular Signals Signals are Angular's built-in **reactive state primitive**. ```typescript count = signal(0); increment() { this.count.update(value => value + 1); } ``` Template: ```html <p>{{ count() }}</p> ``` Computed state: ```typescript doubleCount = computed(() => this.count() * 2); ``` Side effects: ```typescript effect(() => { console.log(this.count()); }); ``` Signals are particularly useful for **local and shared state without needing RxJS for everything**. A service can also expose signals: ```typescript @Injectable({ providedIn: 'root' }) export class CartService { private items = signal<Product[]>([]); readonly cartItems = this.items.asReadonly(); addItem(product: Product) { this.items.update(items => [...items, product]); } } ``` --- ## When should you use each? | Approach | Best For | | ------------------------ | ------------------------------------------------- | | `@Input()` / `@Output()` | Parent-child communication | | Service | Shared/simple application state | | Signals | Local/shared reactive state | | RxJS | Async streams and event-based/reactive operations | | NgRx | Large, complex, centralized application state | ### Interview answer > **I choose state management based on the scope and complexity of the state. For parent-child communication, I use Input and Output. For shared state with relatively simple business logic, I prefer a service, often using Signals or RxJS. Angular Signals are useful for reactive local and shared state with less boilerplate. For large applications where state transitions, side effects, caching, and debugging become complex, I use NgRx with actions, reducers, selectors, and effects. I avoid NgRx for simple state because it can introduce unnecessary complexity.**

    About NUnit test cases

    NUnit is a widely used unit-testing framework for .NET. A test class is a plain class containing methods marked with [Test]; the test runner discovers them, runs each one in isolation and reports pass or fail based on assertions. Core building blocks: - [TestFixture] (optional in modern NUnit) marks a class that contains tests. - [Test] marks a single test method. - [TestCase(...)] runs the same test with different inputs, which avoids copy-pasted tests. - [SetUp] / [TearDown] run before and after every test; [OneTimeSetUp] / [OneTimeTearDown] run once per fixture. - Assert.That(actual, Is.EqualTo(expected)) is the constraint-based assertion style NUnit recommends. Example: public class PriceCalculatorTests { private PriceCalculator _calculator = null!; [SetUp] public void SetUp() => _calculator = new PriceCalculator(); [TestCase(100, 10, 90)] [TestCase(50, 0, 50)] public void Applies_discount(decimal price, decimal percent, decimal expected) { var result = _calculator.Apply(price, percent); Assert.That(result, Is.EqualTo(expected)); } [Test] public void Rejects_negative_discount() => Assert.Throws<ArgumentOutOfRangeException>(() => _calculator.Apply(100, -5)); } Good practices interviewers look for: - Follow Arrange-Act-Assert so each test reads clearly. - Test one behaviour per test and name it after that behaviour. - Keep tests independent: no shared mutable state, no reliance on execution order. - Replace slow or external dependencies (database, HTTP, clock) with fakes or mocks such as Moq or NSubstitute. - Run tests in CI on every pull request with "dotnet test". How NUnit compares with xUnit and MSTest: all three are mature. xUnit creates a new class instance per test and uses constructor/IDisposable instead of [SetUp]/[TearDown]; NUnit has richer attributes (TestCaseSource, Category, Retry) and the constraint model. Choosing one matters less than writing focused, deterministic tests.

    Array vs List<T> and IEnumerable<T> vs IQueryable<T> difference

    These are two separate comparisons, so answer them separately. Array vs List<T> - An array has a fixed length set when it is created; List<T> grows automatically (it wraps an internal array and doubles capacity when full). - Arrays are slightly faster and lighter, and are the natural choice for fixed-size data, buffers or performance-critical loops. - List<T> adds Add, Insert, Remove, Contains, Sort and more, so it is the default choice for collections whose size changes. - Both give O(1) index access. Inserting or removing in the middle of a List<T> is O(n) because elements shift. IEnumerable<T> vs IQueryable<T> - IEnumerable<T> represents an in-memory sequence. LINQ operators run as C# code (delegates) after the data is in memory — this is LINQ to Objects. - IQueryable<T> holds an expression tree. A provider such as Entity Framework Core translates that tree into SQL and runs it in the database. Why it matters: var users = db.Users.Where(u => u.IsActive).Take(10).ToList(); // IQueryable: SQL has WHERE IsActive = 1 and TOP/LIMIT 10 IEnumerable<User> all = db.Users; var users2 = all.Where(u => u.IsActive).Take(10).ToList(); // IEnumerable: loads every user row, then filters in memory The second version can pull an entire table across the network. Keep queries as IQueryable while you are still filtering, sorting and paging, and materialise with ToList/ToListAsync only at the end. Rule of thumb: return IQueryable only inside the data layer when callers must compose queries; expose IEnumerable or a concrete list to the rest of the application so database queries do not leak everywhere.

    Can DBcontext with register as singleton?

    Technically you can register a DbContext as a singleton, but you should not. DbContext is designed to be a short-lived unit of work, and AddDbContext registers it as scoped (one instance per HTTP request) for good reasons. Problems with a singleton DbContext: - It is not thread-safe. Concurrent requests share one instance, which causes "A second operation was started on this context instance before a previous operation completed" and corrupted state. - The change tracker keeps every entity it has ever loaded, so memory grows for the life of the application and later queries return stale tracked data. - A failed SaveChanges leaves the context in a bad state that affects every later request. - Scoped services that depend on it (or that it depends on) cause captive-dependency problems. Correct options: - Web apps: services.AddDbContext<AppDbContext>(...) — scoped per request. - High-throughput apps: services.AddDbContextPool<AppDbContext>(...) reuses instances safely by resetting them between requests. - Singletons and background services that need the database: inject IDbContextFactory<AppDbContext> and create a short-lived context per operation. public sealed class ReportWorker(IDbContextFactory<AppDbContext> factory) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken ct) { await using var db = await factory.CreateDbContextAsync(ct); var pending = await db.Reports.Where(r => !r.Sent).ToListAsync(ct); // ... } } Alternatively, inject IServiceScopeFactory and create a scope per unit of work. Summary for the interview: DbContext should be scoped or created per operation, never a singleton; use pooling or a factory when you need performance or access from a singleton.

    Compare background services, queues, and scheduled jobs for long-running work in ASP.NET Core.

    ASP.NET Core requests should finish quickly, so long-running work is moved out of the request. The three common options solve different problems. 1. Hosted / background services (IHostedService, BackgroundService) - Run inside the web process for its whole lifetime. - Good for continuous in-process work: polling, consuming a queue, cache warming. - Limitation: work is lost if the process restarts or is scaled down, and every instance runs its own copy unless you coordinate. 2. Queues (Azure Service Bus, RabbitMQ, Amazon SQS, Kafka) - The API writes a message and returns 202 Accepted with a status URL; one or more workers process messages independently. - Gives durability, retries, dead-letter queues and horizontal scaling of workers. - Handlers must be idempotent because messages can be delivered more than once. - Use the outbox pattern so the database change and the message are not lost or duplicated when one of them fails. 3. Scheduled jobs (Hangfire, Quartz.NET, Azure Functions timer triggers, cron) - Run at a time or interval: nightly reports, cleanup, billing runs. - Need persistence and distributed locking so a job does not run twice across instances. Choosing: - User-triggered work that may take seconds or minutes (export, video processing, email blast): queue plus worker. - Recurring time-based work: a scheduler with persistent storage. - Light in-process background loops: BackgroundService, usually reading from a Channel<T> or a durable queue. Practical details interviewers like to hear: pass CancellationToken and honour shutdown; never capture scoped services (like DbContext) in a singleton — create a scope per message; add retries with backoff, poison-message handling and monitoring of queue length; expose job status to the UI instead of keeping an HTTP request open.

    Compare scoped, transient, and singleton dependency injection lifetimes in .NET with practical failure examples.

    The three lifetimes control how long the container keeps an instance. - Transient: a new instance every time it is resolved. Use for lightweight, stateless services. - Scoped: one instance per scope — in ASP.NET Core, per HTTP request. Use for per-request state such as DbContext or the current user. - Singleton: one instance for the application's lifetime. Use for thread-safe, stateless or shared resources: configuration, caches, HttpClient handlers via IHttpClientFactory. Practical failure examples: 1. Captive dependency — a singleton depends on a scoped service: services.AddSingleton<ReportService>(); // holds AppDbContext services.AddDbContext<AppDbContext>(); // scoped The singleton keeps the first request's DbContext forever: stale data, thread-safety exceptions and memory growth. ASP.NET Core's scope validation (on by default in Development) throws "Cannot consume scoped service from singleton". Fix: make the consumer scoped or use IServiceScopeFactory / IDbContextFactory. 2. Mutable state in a singleton: public class CartService { public List<Item> Items { get; } = new(); } // registered as singleton Every user shares the same cart. Fix: scoped lifetime or store state per user. 3. Transient IDisposable resolved from the root container: instances are tracked until the app stops, which leaks memory. Resolve within a scope. 4. Creating HttpClient per call (transient, manually) can exhaust sockets. Use IHttpClientFactory, which manages handler lifetimes. Rules of thumb: a service may depend only on services with an equal or longer lifetime; singletons must be thread-safe; enable ValidateScopes and ValidateOnBuild to catch mistakes at startup.

    Compare server-side filtering with client-side filtering for a React data grid backed by ASP.NET Core.

    The decision depends on data size, security and how the grid is used. Client-side filtering (load everything once, filter in React): - Pros: instant filtering and sorting, no extra requests, simple API. - Cons: only works for small datasets (a few thousand rows), large initial payload, memory use on low-end devices, and you must still make sure the user is allowed to see every row you send. Server-side filtering (React sends filters, sorting and page info to ASP.NET Core): - Pros: scales to millions of rows, small payloads, the database uses indexes, and authorization is enforced on the server for every query. - Cons: a request per change and more API design work. A good server-side design: GET /api/orders?status=Shipped&search=acme&sort=-createdAt&page=2&pageSize=50 - Validate and whitelist filter and sort fields; never build SQL from raw strings. - Build an IQueryable in EF Core and apply Where/OrderBy/Skip/Take so filtering happens in SQL. - Prefer keyset (cursor) pagination for large tables; OFFSET gets slower on deep pages. - Return items plus total count or a next cursor. - Add indexes for the common filter and sort columns. On the React side: - Keep filter state in the URL so it survives refresh and can be shared. - Debounce text search (about 300 ms) and cancel stale requests with AbortController or a library such as TanStack Query. - Show loading and empty states and keep the previous page visible while the next loads. Many real apps use a hybrid: server-side filtering for the main grid, client-side filtering only within the currently loaded page or for small lookup lists.

    Dependency Injection Service Lifetimes – Singleton, Scoped, and Transient

    Dependency injection (DI) lets a class receive its dependencies instead of creating them. In ASP.NET Core you register services in Program.cs and the built-in container creates them with one of three lifetimes. Singleton — services.AddSingleton<IClock, SystemClock>(); - One instance for the whole application. - Must be thread-safe and should not hold per-user state. - Examples: configuration objects, in-memory caches, IHttpClientFactory, logging. Scoped — services.AddScoped<IOrderService, OrderService>(); - One instance per scope; in web apps that means per HTTP request. - Examples: DbContext (AddDbContext registers it scoped), unit-of-work, current user context. Transient — services.AddTransient<IEmailBuilder, EmailBuilder>(); - A new instance every time it is requested. - Examples: lightweight, stateless helpers. How to choose: - Does it hold state shared by everyone and is it thread-safe? Singleton. - Does it hold state for one request, or depend on DbContext? Scoped. - Is it cheap and stateless? Transient (scoped also works). Common mistakes: - Injecting a scoped service into a singleton (captive dependency). The scoped object lives forever and causes stale data and concurrency bugs. ASP.NET Core detects this in Development with scope validation. - Storing request data in a singleton field, which leaks data between users. - Resolving transient IDisposable services from the root provider, which keeps them alive until shutdown. In background services, create a scope explicitly: using var scope = scopeFactory.CreateScope(); var orders = scope.ServiceProvider.GetRequiredService<IOrderService>();

    Dependency Injection: What is dependency injection in the context of .NET?

    Dependency injection is a technique where an object receives the things it depends on from the outside instead of constructing them itself. It is one way to apply the Dependency Inversion Principle: high-level code depends on abstractions, and a container supplies the concrete implementations. Without DI: public class OrderService { private readonly SqlOrderRepository _repo = new SqlOrderRepository(); // hard-wired } With DI (constructor injection): public class OrderService(IOrderRepository repo, ILogger<OrderService> logger) { public Task PlaceAsync(Order order) => repo.AddAsync(order); } builder.Services.AddScoped<IOrderRepository, SqlOrderRepository>(); builder.Services.AddScoped<OrderService>(); When ASP.NET Core creates a controller or service, the built-in container (Microsoft.Extensions.DependencyInjection) reads the constructor, resolves each dependency and its dependencies, and manages their lifetimes (transient, scoped, singleton). Benefits: - Loose coupling: swap implementations (SQL vs in-memory, real vs fake email sender) without changing the consumer. - Testability: pass mocks or fakes in unit tests. - Central configuration of object creation and lifetimes. - Cross-cutting features such as logging, options and HttpClientFactory plug in easily. Forms of injection: constructor injection (preferred, makes dependencies explicit), method injection ([FromServices] in an action, or a parameter in minimal APIs) and property injection (not supported by the built-in container). Avoid the service-locator anti-pattern — calling serviceProvider.GetService inside business code — because it hides dependencies. A constructor with many parameters is also a sign the class has too many responsibilities.

    Describe a practical strategy for unit, integration, contract, and end-to-end testing in a .NET full-stack product.

    Use a test pyramid shaped by risk: many fast unit tests, fewer integration and contract tests, and a small set of end-to-end tests for critical journeys. Unit tests (xUnit/NUnit on the backend, Vitest/Jest with React Testing Library on the frontend) - Cover domain rules, validation, calculations and component behaviour. - No database or network; dependencies replaced with fakes. - Run in seconds on every commit. Integration tests (backend) - Use WebApplicationFactory to host the real API in memory. - Run against a real database engine in a disposable container (Testcontainers for SQL Server or PostgreSQL) rather than the EF in-memory provider, which hides SQL behaviour. - Test endpoints end to end inside the service: routing, model binding, validation, authorization, EF mappings, migrations and error responses. Contract tests - Protect the boundary between the React app (consumer) and the API (provider), or between microservices. - Pact-style consumer-driven contracts, or validating responses against a published OpenAPI schema, catch breaking changes before deployment. End-to-end tests (Playwright or Cypress) - A handful of journeys: sign in, the main purchase or create flow, payment, permissions. - Run against a deployed test environment with seeded data; keep them stable with test IDs and explicit waits for state, not fixed sleeps. Supporting practices: - Run unit and integration tests on every pull request, E2E on merge or before release. - Track flaky tests and fix or quarantine them quickly. - Measure coverage as a signal, not a target; focus on critical paths and bug-prone areas. - Add a regression test for every production bug. - Include non-functional checks where relevant: accessibility (axe), performance smoke tests, security scanning. The goal is fast feedback for developers and confidence that a release will not break the paths that make money or protect data.

    Design a React and ASP.NET Core checkout flow that remains safe when a customer submits the same payment twice.

    The key is idempotency: the same payment request processed twice must charge the customer only once. Frontend (React) - Disable the Pay button and show progress after the first click. - Generate an idempotency key (a UUID) when the checkout attempt starts, and send it with every retry of that attempt, for example in an Idempotency-Key header. - On a timeout, do not create a new attempt automatically; poll the order status or retry with the same key. Backend (ASP.NET Core) 1. Create the order first with status PendingPayment, inside a transaction. 2. Store the idempotency key with a unique constraint (user or merchant + key). If the key already exists, return the stored result instead of processing again; if it is still in progress, return 409 or 202 with the current status. 3. Call the payment provider and pass the same idempotency key — Stripe, Razorpay and most gateways support this, so even provider retries are safe. 4. Record the result and move the order to Paid or Failed. Webhooks - The provider confirms payment asynchronously. Verify the webhook signature, de-duplicate by provider event ID, and make the status update idempotent ("set Paid if not already Paid"). - Treat the webhook as the source of truth; the redirect back to the site can be lost. Concurrency and consistency - Use optimistic concurrency (a rowversion column) on the order so two parallel requests cannot both move it from Pending to Paid. - Use the outbox pattern to publish "OrderPaid" events reliably for emails and fulfilment. Reconciliation - A scheduled job compares orders stuck in Pending with the provider's records and fixes or refunds them. Also mention security: never trust amounts from the client; compute totals on the server, use HTTPS, and keep card data with the provider (PCI scope reduction).

    Design a caching strategy using Redis for a .NET product API, including invalidation and cache-stampede protection.

    Use cache-aside with Redis as a distributed cache in front of the database. Read path: 1. Build a key from the request, e.g. product:{id} or products:list:{category}:{page}. 2. Try Redis. On a hit, return the cached value. 3. On a miss, load from the database, write it to Redis with a TTL, and return it. In .NET, use IDistributedCache, the newer HybridCache (in-memory L1 plus Redis L2, with built-in stampede protection) or StackExchange.Redis directly. Serialize with System.Text.Json and keep values small. Invalidation: - On writes, delete or update the affected keys after the database commit (product:{id} and any list keys that contain it). - For list caches that are hard to track, use versioned keys: store products:version and include it in list keys; incrementing it invalidates all lists at once. - In multi-service systems, publish change events (outbox plus message bus or Redis pub/sub) so every service evicts its copies. - Always set a TTL as a safety net so stale data eventually expires; add random jitter so keys do not expire at the same moment. Cache-stampede protection (many requests miss at once and hammer the database): - Single-flight: only one request rebuilds a key while others wait — a per-key SemaphoreSlim in process, or a short Redis lock (SET key value NX PX 5000) across instances. - Stale-while-revalidate: keep serving the old value while one request refreshes it in the background. - Early refresh: refresh popular keys shortly before they expire. Other details: - Decide what is safe to cache: never mix data between users or tenants — include the tenant or user in the key when data is personalised. - Handle Redis outages gracefully: fall back to the database with timeouts and a circuit breaker. - Cache negative results (not found) briefly to stop repeated lookups for missing IDs. - Monitor hit ratio, memory use and evictions.

    Design a dashboard API that aggregates millions of records without running expensive queries on every page load.

    Avoid computing aggregates from raw rows on every request. Precompute and cache instead. 1. Pre-aggregate - Maintain summary tables (daily totals by customer, region or status) updated incrementally when data changes, or by a scheduled job every few minutes. - In SQL Server, an indexed view can keep simple aggregates up to date automatically; in PostgreSQL, a materialized view refreshed on a schedule. - For very large analytical workloads, use columnstore indexes or a separate analytics store (data warehouse, ClickHouse) fed by ETL or change data capture. 2. Cache the results - Cache dashboard responses in Redis keyed by tenant, filters and time range, with a TTL matching how fresh the data must be (for example 1–5 minutes). - Use stale-while-revalidate so users never wait for a rebuild. 3. Design the API around the dashboard - One endpoint per widget or a batched endpoint, returning only the numbers needed, not raw rows. - Limit time ranges and granularity (hourly for the last day, daily for the last year). - Paginate any drill-down lists with keyset pagination. 4. Query and index tuning - Index the columns used for filtering and grouping (tenant, date); use covering indexes. - Read from a replica so dashboard load does not affect transactional traffic. - Use asynchronous queries with timeouts and cancellation. 5. Freshness and UX - Show "last updated at" on the dashboard. - For near real-time counters, update them from events (increment counters in Redis) instead of re-counting. Trade-off to state clearly: precomputation gives fast, predictable reads in exchange for slightly stale data and extra write or batch work. Agree the acceptable staleness with the business first.

    Design a feature-flag system for gradual releases across a React frontend and .NET backend.

    A feature-flag system lets you deploy code dark and release it gradually without redeploying. Core model - A flag has a key (new-checkout), an enabled state, and targeting rules: percentage rollout, specific users or tenants, environment, country or app version. - Evaluation must be deterministic: hash(flagKey + userId) mod 100 places a user in a stable bucket, so the same user always sees the same variant. Backend (.NET) - Use Microsoft.FeatureManagement or a provider such as LaunchDarkly, Unleash, Flagsmith or Azure App Configuration. - Evaluate flags on the server for anything security- or data-related; never rely only on hiding a button in React. - Cache flag definitions in memory and refresh them periodically or via push, so evaluation needs no network call per request. - Fail safe: if the flag service is unavailable, use the last known value or a safe default. Frontend (React) - Fetch the evaluated flags for the current user from the backend (e.g. GET /api/flags) at startup, or use the provider's client SDK. - Expose them through a context or hook: if (useFlag('new-checkout')) ... - Avoid flicker: load flags before rendering the affected UI, or render a neutral placeholder. Rollout process - Release to internal users, then 1%, 10%, 50%, 100%, watching error rates, latency and business metrics at each step. - Keep a kill switch to turn a feature off instantly. - Keep frontend and backend consistent: the API must accept both old and new request shapes while a flag is partially on. Governance - Audit who changed which flag and when. - Give each flag an owner and an expiry; remove flags and dead code paths after full rollout to avoid flag debt. - Test both flag states in automated tests.

    Design a multi-tenant .NET application that prevents one customer from reading another customer’s data.

    Tenant isolation must be enforced on the server at every layer, not just in the UI. 1. Establish the tenant reliably - Derive the tenant from the authenticated identity (a tenant_id claim in the token issued by your identity provider), not from a header or query string the client can change. - If a user can belong to several tenants, validate the requested tenant against the user's memberships on every request. 2. Enforce isolation in data access - Shared database: every tenant-owned table has a TenantId column. In EF Core, apply a global query filter: modelBuilder.Entity<Invoice>().HasQueryFilter(i => i.TenantId == _tenantContext.TenantId); and set TenantId automatically on insert in SaveChanges. - Add defence in depth with SQL Server Row-Level Security or PostgreSQL RLS policies, so even a bug or raw SQL query cannot cross tenants. - Include TenantId in unique indexes and foreign keys so references cannot point to another tenant's rows. - For stricter requirements, use schema-per-tenant or database-per-tenant isolation, at the cost of more operational work. 3. Authorization - Check access to each resource by ID and tenant (resource-based authorization), returning 404 rather than 403 so IDs cannot be probed. - Avoid guessable sequential IDs in URLs where possible. 4. Other shared resources - Prefix cache keys, blob paths, search indexes and message topics with the tenant ID. - Background jobs must carry the tenant ID explicitly, because there is no HTTP request. - Logs and exports should be tenant-scoped. 5. Verify it - Automated tests that log in as tenant A and attempt to read, update and list tenant B's data through every endpoint. - Code review and static checks for queries that bypass the filter (IgnoreQueryFilters, raw SQL). - Penetration testing focused on IDOR (insecure direct object reference) issues.

    Design a rate-limiting strategy for login, search, and authenticated write endpoints in ASP.NET Core.

    Different endpoints need different limits, because the threat and the normal usage differ. Login - Goal: stop credential stuffing and brute force. - Limit per IP and per account (for example 5 attempts per minute per username, with a longer lockout or exponential backoff after repeated failures). - Add CAPTCHA after several failures, and alert on unusual spikes. Return the same error for a wrong username or password so accounts cannot be enumerated. Search - Goal: protect expensive queries and scraping while keeping the UX smooth. - Token bucket per user or IP, allowing short bursts (typing) but capping sustained rates, e.g. 30 requests per 10 seconds. - Debounce on the client and cache popular queries on the server. Authenticated writes (create order, post comment) - Limit per user ID rather than IP, since many users can share one IP (offices, mobile networks). - Lower limits for costly or abusable actions (sending emails, invitations). Implementation in ASP.NET Core (.NET 7+): builder.Services.AddRateLimiter(o => { o.RejectionStatusCode = 429; o.AddPolicy("login", ctx => RateLimitPartition.GetFixedWindowLimiter( ctx.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new FixedWindowRateLimiterOptions { PermitLimit = 5, Window = TimeSpan.FromMinutes(1) })); o.AddPolicy("writes", ctx => RateLimitPartition.GetTokenBucketLimiter( ctx.User.FindFirst("sub")?.Value ?? "anon", _ => new TokenBucketRateLimiterOptions { TokenLimit = 20, TokensPerPeriod = 10, ReplenishmentPeriod = TimeSpan.FromSeconds(10) })); }); app.UseRateLimiter(); Then apply [EnableRateLimiting("login")] or RequireRateLimiting("writes") on endpoints. Production considerations: - The built-in limiter is per process. With several instances, use a distributed store (Redis) or enforce limits at the gateway or WAF (Azure Front Door, Cloudflare, API Management). - Behind a proxy, configure forwarded headers correctly so you limit the real client IP. - Return 429 with a Retry-After header, log rejections and monitor them. - Exempt or separately limit health checks and trusted internal callers.

    Design a search autocomplete API that is fast, rate-limited, accessible, and safe from query injection.

    Autocomplete must answer in well under 100 ms, so it needs a purpose-built design. Data and querying - Use a prefix-friendly index: a search engine (Elasticsearch/OpenSearch with edge n-grams or completion suggesters, Azure AI Search suggesters) or, for small data, a database index on a normalized column with LIKE 'term%'. - Avoid LIKE '%term%' on large tables because it cannot use a normal index. - Return only a handful of fields and the top 5–10 suggestions, ranked by popularity. Safety from injection - Always use parameterized queries (EF Core LINQ or SqlParameter); never concatenate user input into SQL or search DSL strings. - Escape LIKE wildcards (% and _) in user input. - Validate length (for example 2–100 characters) and normalise whitespace and case. Performance - Cache popular prefixes in memory or Redis for a short time. - Add a request timeout and CancellationToken so abandoned requests stop work. - On the client, debounce input by about 200–300 ms, require a minimum length, and cancel in-flight requests with AbortController when the user keeps typing. Rate limiting - Use a token-bucket limiter per user or IP that allows bursts while typing but blocks scraping, and return 429 with Retry-After. Accessibility (often forgotten in interviews) - Follow the WAI-ARIA combobox pattern: an input with role="combobox", aria-expanded and aria-controls, a listbox of options, and aria-activedescendant for the highlighted item. - Support keyboard navigation (arrow keys, Enter, Escape) and announce result counts with a polite live region. - Do not move focus away from the input while the user types. Also protect privacy: do not suggest other users' private data, and filter suggestions by the caller's permissions or tenant.

    Design a secure file-upload feature with React and ASP.NET Core, including validation, storage, and malware scanning.

    Treat every uploaded file as untrusted. Frontend (React) - Restrict choices with the accept attribute and check size before upload for quick feedback — but treat these as UX only, since they can be bypassed. - For large files, upload directly to storage using a short-lived pre-signed URL (Azure Blob SAS or S3 pre-signed URL) issued by the API, and show progress. Backend validation (ASP.NET Core) - Enforce size limits on the server (RequestSizeLimit, Kestrel and form options). - Allow-list extensions and verify the real type from the file's magic bytes, not the Content-Type header or file name. - Generate your own random file name and storage path; never use the user's file name in a path (prevents path traversal and overwrites). Keep the original name only as escaped metadata. - For images, re-encode them (for example with ImageSharp) to strip metadata and malformed payloads. Storage - Store files outside the web root, in a private blob container or bucket. - Upload first to a quarantine container. Only after scanning, move the file to the clean container. - Serve downloads through authorized endpoints or short-lived signed URLs, with Content-Disposition: attachment and X-Content-Type-Options: nosniff, preferably from a separate domain so uploaded HTML or SVG cannot run scripts on your main site. Malware scanning - Scan asynchronously: a blob-created event or queue message triggers a scanner (Microsoft Defender for Storage, ClamAV in a container, or a commercial API). - Track status (Pending, Clean, Infected) in the database and only allow downloads of Clean files; delete or isolate infected ones and alert. Authorization and auditing - Check that the user may upload to and read the target resource, scoped by tenant. - Apply rate limits and per-user quotas. - Log uploads, scans and downloads for auditing.

    Design a zero-downtime deployment process for an ASP.NET Core API with database changes.

    Zero-downtime deployment needs both the application rollout and the database changes to be backward compatible. Application rollout - Run at least two instances behind a load balancer, or use deployment slots in Azure App Service: deploy to staging, warm it up, then swap. - Use rolling or blue-green deployments in Kubernetes or containers, with readiness probes so traffic only reaches instances that are ready. - Handle graceful shutdown: stop accepting new requests and let in-flight requests finish (configure the host shutdown timeout). Database changes: expand and contract Old and new versions of the code run at the same time, so every schema change must work with both. 1. Expand: add new nullable columns or tables, new indexes (online where supported), and keep old columns. Deploy the migration before the code. 2. Deploy code that writes to both old and new structures and reads safely from either. 3. Backfill data in small batches to avoid long locks. 4. Switch reads to the new structure. 5. Contract: in a later release, remove old columns and code once no running version uses them. Never rename or drop a column in the same release as the code that stops using it. Tooling - Run EF Core migrations as a separate pipeline step or idempotent script (dotnet ef migrations script --idempotent), not on application startup across several instances. - Review generated SQL for locking operations on large tables. Safety nets - Health checks and automated smoke tests after deployment. - Feature flags to turn new behaviour on gradually and off instantly. - Monitor error rates and latency; roll back by swapping slots back. Because schema changes are backward compatible, the previous version still works. - Take a backup or point-in-time restore point before risky migrations.

    Design an audit trail for sensitive changes that is useful to support teams and resistant to tampering.

    An audit trail must answer "who changed what, when, from where and why", and it must be trustworthy. What to record - Actor (user ID, impersonator if any, service identity), timestamp in UTC, action, entity type and ID, tenant, before and after values of changed fields, request or correlation ID, IP address, user agent, and a reason when the action requires one. - Mask or omit secrets and sensitive values (passwords, full card numbers) but record that they changed. How to capture it - Write audit records in the same database transaction as the business change, so a change cannot happen without its audit entry. In EF Core, a SaveChanges interceptor can read the ChangeTracker and create audit rows automatically. - For high volume, use an outbox to ship audit events to a dedicated store (a separate database, Azure Data Explorer, or an append-only log). Tamper resistance - Make the audit store append-only: the application identity can insert but not update or delete (enforced with database permissions). - Chain records with hashes: each entry stores hash(previous hash + entry content). Any modification breaks the chain and can be detected by a verification job. - Periodically anchor the latest hash or export batches to immutable storage (Azure Blob immutability policies, S3 Object Lock / WORM). - Restrict access to audit data and audit who reads it. - Use synchronised clocks and server-side timestamps. Useful for support teams - Provide a searchable UI: filter by entity, user, time range and action, with a readable diff ("Status: Pending to Approved"). - Link entries with correlation IDs to application logs. - Define retention to meet legal requirements, and archive older data. Separate audit logs (business evidence, long retention) from technical logs (debugging, short retention); they have different consumers and rules.