📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Design a file storage and sharing service on Azure Blob Storage, like the document area of a client portal: users upload files up to a few gigabytes, share them with links that expire, and every file is scanned for malware before anyone can download it. Walk me through uploads, downloads, sharing links, scanning, quotas and keeping it secure.

A full file storage and sharing design: requirements and storage estimates, direct-to-blob uploads with user delegation SAS and block blobs, metadata in Azure SQL, a quarantine-then-scan pipeline with Defender for Storage, expiring share links checked by the API, quotas, lifecycle tiers, and security and privacy controls, on Azure with .NET.

Senior SystemDesign Advanced azure blob-storage file-upload malware-scanning sas-tokens system-design

🎯 Key points

  • Clarify: file sizes, users, share types (internal, external link), retention, scanning, residency
  • Bytes never pass through the API: clients upload directly with a short-lived, create-only user delegation SAS
  • Quota reserved atomically (conditional UPDATE) before issuing the SAS, confirmed on commit, released by a sweeper
  • Large files as block blobs: parallel Put Block then Put Block List; resumable
  • Metadata in Azure SQL; blob name is a GUID, never the user's file name
  • Quarantine container, scan (Defender for Storage malware scanning or another engine), server-side magic-byte check, promote only Clean files
  • Share links are our own revocable, audited tokens that resolve to a seconds-long read SAS
  • Abuse controls: per-user upload rate limits, max size in the SAS flow, WAF at the edge; private endpoints, managed identity, no account keys

⏱ 30-second answer

The key idea: file bytes never go through my API. The client asks the API for an upload; the API atomically reserves quota (one conditional update, so parallel uploads can't overshoot) and returns a short-lived, create-only user delegation SAS for a GUID-named blob in a quarantine container. The client uploads directly to Blob Storage, in parallel blocks for big files. A BlobCreated event triggers malware scanning (Defender for Storage, or a scanning service of your choice); only clean files, whose real type is checked server-side, are promoted and marked available. Metadata lives in Azure SQL. Sharing links are my own revocable tokens: the API checks them and redirects to a read SAS valid for seconds. The trade-off: direct uploads scale and cost little, but you give up inline validation, so the scan-and-promote step becomes the gate.

🗣 Full answer (senior)

How I would answer this in an interview

"First the requirements: [20,000] users across [300] business clients, files from a few KB to [5 GB], sharing internally and with external people by link, links that expire, every file scanned before download, data in Australia, and retention of [7 years] for some document types. The core design decision is that the API handles metadata and permissions and Blob Storage handles bytes. Streaming gigabytes through ASP.NET Core ties up threads, memory and bandwidth for no benefit.

So an upload is three steps. The client calls POST /files with name, size and content type. The API checks permissions and reserves quota, creates a metadata row with status Uploading, and returns a user delegation SAS that can only create one blob, a GUID name in the quarantine container, valid for [15 minutes]. The client uploads blocks in parallel and commits the block list, so a 5 GB upload over a flaky connection resumes rather than restarts. A Blob Created event goes to Event Grid, the file is scanned, and a function moves clean files to the main container and sets status Available; malicious files are deleted and the user is told. Downloads always go through the API: it checks access, logs it, and redirects to a read SAS that lives for [60 seconds].

For example, at [company] we [proxied uploads through the API] and [large uploads caused thread-pool and memory pressure]; [moving to direct SAS uploads] [cut API memory by 70% and removed upload timeouts].

Sharing links are rows in my database with an expiry, optional password and download limit, so I can revoke them. A SAS URL handed out for a week can't be revoked without rotating keys, which is why I never give one to a user directly.

The mistake I see is long-lived SAS links or account keys in config. Use managed identity, user delegation SAS, private endpoints, and keep SAS lifetimes in minutes."


Requirements

Type Requirement Assumption
Functional Upload, list, download, delete, folders Up to 5 GB per file
Functional Share with users or by external link Expiry, optional password, revocable
Functional Malware scan before download Quarantine until clean
Non-functional Quotas per client plan e.g. 100 GB, 1 TB
Non-functional Australia-only data, 7-year retention for records Lifecycle and immutability policies
Non-functional Upload start p95 < 200 ms Bytes go direct to storage

Capacity estimate

Quantity Arithmetic Result
Uploads 20,000 users × 5/day 100,000/day ≈ 1.2/s, peak ×5 ≈ 6/s
Average size mix of PDFs and images ≈ 4 MB
New storage 100,000 × 4 MB × 365 ≈ 146 TB/year
Downloads 3 × uploads ≈ 300,000/day, ~1.2 TB/day egress
Metadata rows 36.5M/year × ~1 KB ≈ 37 GB/year in Azure SQL

Storage dominates cost, so lifecycle tiering matters more than compute.

High-level design

Client ── POST /files ──► Files API (ASP.NET Core) ──► Azure SQL (metadata, quotas, shares)
   │ ◄── user delegation SAS (create-only, 15 min)
   │
   └── PUT blocks / commit ──► Blob: quarantine container (private endpoint for internal callers)
                                   │ BlobCreated
                                   ▼
                         Defender for Storage scan ──► result event ──► Promote function
                                                                     ├─ Clean: copy to files container, status=Available
                                                                     └─ Malicious: delete, status=Rejected, notify
Download: GET /files/{id} or /s/{shareToken} ──► API checks access + audit ──► 302 to read SAS (60 s)

Sharing options

Approach Revocable Audit per download Risk
Long-lived SAS URL No (only by key rotation) No Leaked link works until expiry
Stored access policy SAS Yes, per policy (max 5 per container) No Coarse
Our share token → short read SAS Yes, per link Yes Needs API on download path

Production example

A client document portal storing [90 TB] moved to direct uploads with block blobs and a quarantine-scan step: API memory dropped from [3 GB to 900 MB] per instance, failed large uploads fell from [8% to under 1%], and lifecycle rules to Cool after 30 days and Archive after a year cut storage cost by [about 45%].

🔍 What the interviewer is checking

Checks that the candidate keeps bytes off the API, uses scoped short-lived SAS correctly, gates downloads on a malware scan, and designs revocable sharing, quotas and lifecycle.

Green flags

  • Direct-to-blob uploads with create-only user delegation SAS
  • Block blobs for large, resumable uploads
  • Quarantine, scan and promote pipeline
  • Share tokens that resolve to seconds-long read SAS; audited downloads
  • Lifecycle tiers and retention

Red flags

  • Proxying gigabytes through ASP.NET Core
  • Long-lived SAS or account keys
  • Files downloadable before scanning
  • User-supplied file names as blob paths

📚 Learn in depth

1. Why not stream through the API

Proxying 5 GB through Kestrel holds a connection and buffers for minutes, consumes egress twice, and makes your API instances the bottleneck. Direct-to-blob uploads let Azure Storage absorb the bandwidth; the API only does the cheap, transactional part.

2. SAS types

  • User delegation SAS: signed with a key obtained via Entra ID (the API's managed identity calls Get User Delegation Key). No account keys involved; it can be invalidated by revoking user delegation keys. Preferred.
  • Service SAS / account SAS signed with the account key: avoid; disable shared-key authorisation on the account where possible. Scope each SAS to one blob, minimal permissions (c/w for upload, r for download), a short expiry and HTTPS only.

3. Large uploads

Block blobs: the client splits the file into blocks (for example 8 MB), uploads them in parallel with Put Block, then commits with Put Block List. Uncommitted blocks don't form a blob, and if a block fails only it is retried. A browser can use the Azure Storage JS SDK; a .NET client uses BlockBlobClient or BlobClient.UploadAsync with StorageTransferOptions for parallelism.

4. The scan-and-promote pipeline

quarantine/{tenant}/{fileId}  ── BlobCreated ─► scan ─► Clean  ─► copy to files/{tenant}/{fileId}, delete quarantine copy
                                                     └► Malicious ─► delete, Rejected

Defender for Storage on-upload malware scanning writes the result as a blob index tag and can publish results to Event Grid. Your promote function reacts to that result. Also verify on commit: actual size matches the reserved size, the content type is allowed (check magic bytes, not just the extension), and record a SHA-256 for integrity.

5. Metadata model

Files(Id, TenantId, OwnerId, FolderId, DisplayName, BlobName, SizeBytes, ContentType, Sha256, Status, ScanResult, CreatedAt, DeletedAt) and Shares(Token, FileId, CreatedBy, ExpiresAt, PasswordHash, MaxDownloads, Downloads, RevokedAt). The user's file name is display metadata only; the blob name is a GUID, which avoids path traversal and enumeration.

6. Quotas

Reserve on request (UsedBytes + ReservedBytes + size <= Quota in one conditional update), convert to used on successful commit, release on expiry by a sweeper. Without reservation, ten parallel uploads can each pass the check.

7. Lifecycle, retention and deletion

Lifecycle management rules: Hot → Cool after 30 days without access, → Cold or Archive later. Archive needs hours of rehydration, so tell users. Soft delete and versioning protect against mistakes and ransomware; immutable (WORM) policies for records that must be kept. Deleting a file deletes the blob and its versions after the retention period.

8. Security and privacy

Private endpoints for server-side access, managed identity with Storage Blob Data roles, shared-key access disabled, Defender for Storage on, Australia East storage with geo-redundancy to Southeast (GRS pairs within Australia). Downloads set Content-Disposition: attachment so HTML files can't run in your domain. Every download is audited, which matters for NDB assessments.

9. AWS mapping

S3 with presigned URLs and multipart upload, GuardDuty Malware Protection for S3, EventBridge, lifecycle to S3 Glacier, DynamoDB or RDS for metadata.

Try it yourself

  1. Generate a user delegation SAS with create-only permission and try to read with it.
  2. Upload a 1 GB file in 8 MB blocks with parallelism 4 vs 1 and compare time.
  3. Upload the EICAR test file to a quarantine container with Defender scanning enabled and watch the result tag.
  4. Fire 10 parallel upload requests against a quota and confirm reservation stops overshoot.
  5. Write a lifecycle policy and validate it with the Azure CLI.

💻 Code

Issuing a create-only user delegation SAS for a direct upload after reserving quota, and a share link that resolves to a 60-second read SAS.

using Azure.Storage.Blobs;
using Azure.Storage.Sas;

namespace FileStore;

public sealed record UploadRequest(string FileName, long SizeBytes, string ContentType);
public sealed record UploadTicket(Guid FileId, Uri UploadUrl, DateTimeOffset ExpiresAt);

public interface IFileRepository
{
    Task<bool> TryReserveQuotaAsync(Guid tenantId, long bytes, CancellationToken ct);
    Task AddAsync(Guid fileId, Guid tenantId, Guid ownerId, UploadRequest r, string blobName, CancellationToken ct);
    Task<(Guid FileId, string BlobName)?> ResolveShareAsync(string token, CancellationToken ct); // checks expiry, revoke, limit
}

public sealed class UploadService(BlobServiceClient blobs, IFileRepository files, TimeProvider clock)
{
    private static readonly HashSet<string> Allowed = ["application/pdf", "image/png", "image/jpeg"];

    public async Task<UploadTicket?> StartAsync(Guid tenantId, Guid userId, UploadRequest r, CancellationToken ct)
    {
        if (!Allowed.Contains(r.ContentType) || r.SizeBytes is <= 0 or > 5L * 1024 * 1024 * 1024) return null;
        if (!await files.TryReserveQuotaAsync(tenantId, r.SizeBytes, ct)) return null; // conditional update in SQL

        var fileId = Guid.NewGuid();
        var blobName = $"{tenantId}/{fileId}"; // never the user's file name
        await files.AddAsync(fileId, tenantId, userId, r, blobName, ct);

        var now = clock.GetUtcNow();
        // Signed with Entra ID via managed identity: no account key anywhere.
        var key = await blobs.GetUserDelegationKeyAsync(now.AddMinutes(-5), now.AddMinutes(20), ct);
        var sas = new BlobSasBuilder
        {
            BlobContainerName = "quarantine", BlobName = blobName, Resource = "b",
            StartsOn = now.AddMinutes(-5), ExpiresOn = now.AddMinutes(15), Protocol = SasProtocol.Https
        };
        sas.SetPermissions(BlobSasPermissions.Create | BlobSasPermissions.Write); // cannot read or list

        var uri = new BlobUriBuilder(blobs.GetBlobContainerClient("quarantine").GetBlobClient(blobName).Uri)
        { Sas = sas.ToSasQueryParameters(key.Value, blobs.AccountName) }.ToUri();
        return new UploadTicket(fileId, uri, sas.ExpiresOn);
    }

    public async Task<Uri?> ResolveShareAsync(string token, CancellationToken ct)
    {
        if (await files.ResolveShareAsync(token, ct) is not { } f) return null; // revocable, audited
        var now = clock.GetUtcNow();
        var key = await blobs.GetUserDelegationKeyAsync(now.AddMinutes(-5), now.AddMinutes(10), ct);
        var sas = new BlobSasBuilder
        {
            BlobContainerName = "files", BlobName = f.BlobName, Resource = "b",
            StartsOn = now.AddMinutes(-1), ExpiresOn = now.AddSeconds(60), Protocol = SasProtocol.Https,
            ContentDisposition = "attachment" // never render user content inline on our domain
        };
        sas.SetPermissions(BlobSasPermissions.Read);
        return new BlobUriBuilder(blobs.GetBlobContainerClient("files").GetBlobClient(f.BlobName).Uri)
        { Sas = sas.ToSasQueryParameters(key.Value, blobs.AccountName) }.ToUri();
    }
}
// Program.cs (excerpt): managed identity, no connection string with a key.
builder.Services.AddSingleton(_ => new BlobServiceClient(
    new Uri(builder.Configuration["Storage:BlobEndpoint"]!), new Azure.Identity.DefaultAzureCredential()));
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddScoped<UploadService>();
{
  "rules": [{
    "name": "tier-old-files", "enabled": true, "type": "Lifecycle",
    "definition": {
      "filters": { "blobTypes": ["blockBlob"], "prefixMatch": ["files/"] },
      "actions": { "baseBlob": {
        "tierToCool": { "daysAfterModificationGreaterThan": 30 },
        "tierToArchive": { "daysAfterModificationGreaterThan": 365 } } }
    }
  }]
}

⚠ Common mistakes

  • Mistake: Streaming uploads and downloads through the API. Why it is wrong: gigabytes tie up connections, memory and bandwidth, and the API becomes the bottleneck. Instead: direct-to-blob with scoped SAS; the API handles metadata and permissions.
  • Mistake: Handing users long-lived SAS URLs as share links. Why it is wrong: they can't be revoked or audited, and leaked links keep working. Instead: your own share tokens that resolve to seconds-long read SAS.
  • Mistake: Account-key SAS or keys in configuration. Why it is wrong: a leaked key gives full access to the account until rotation. Instead: managed identity and user delegation SAS; disable shared-key access.
  • Mistake: Making files downloadable before scanning. Why it is wrong: your portal distributes malware to clients. Instead: quarantine container, scan, promote only clean files.
  • Mistake: Using the user's file name as the blob path. Why it is wrong: collisions, path traversal and enumeration. Instead: GUID blob names; file name is metadata.
  • Mistake: Checking quota without reserving it atomically. Why it is wrong: parallel uploads all pass a read-then-write check and overshoot. Instead: one conditional UPDATE ... WHERE Used + Reserved + @size <= Quota, confirm on commit, release on expiry.
  • Mistake: Trusting the client's content type or extension. Why it is wrong: an .exe renamed to .pdf passes. Instead: after upload, a server-side step reads the first bytes of the blob (a ranged download with the SDK) to check the file signature against the declared type, rejects mismatches, and serves downloads as attachments.
  • Mistake: No limits on who can request upload tickets. Why it is wrong: a compromised account or bot can fill storage and run up cost. Instead: per-user and per-tenant rate limits on POST /files, quotas, and WAF rules at Front Door.
  • Mistake: Keeping everything in the Hot tier forever. Why it is wrong: storage dominates the bill. Instead: lifecycle rules, with Archive rehydration time made clear to users.

🏛 Senior insight: trade-offs

The senior move is splitting the control plane (API: identity, permissions, quotas, audit) from the data plane (Blob Storage: bytes). That keeps the API small and cheap and lets storage do what it's built for. The two planes must still be joined up: the API learns about commits, scan results and failures through Event Grid events, every state change is logged with the file id and tenant, and storage diagnostic logs go to the same Log Analytics workspace so you can trace an upload from ticket to Available. A file stuck in Uploading or Scanning for more than [30 minutes] raises an alert.

Privacy is part of the design: client documents are personal information under the Privacy Act 1988, so storage stays in Australia East/Southeast, every download is audited (who, when, via which link), share links expire by default, and you can tell an NDB assessment exactly who accessed a file.

Option When it fits Cost When not to
Direct SAS upload + async scan Large files, many users Async status UX Tiny files where inline validation is simpler
Proxy through API Small files needing inline transformation API bandwidth and memory Anything over a few MB at scale
Share tokens → short SAS External sharing, audit API on download path Public, static assets (use a CDN)

I measure upload success rate by size band, time from upload to Available (scan latency), quota rejections, storage by tier, egress, and download audit volume.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions sharing with specific users or teams Why: Checks resource-based authorisation for who may read or share a file
    How to answer

    Resource-based authorisation decides using the record itself: its owner, team, tenant or state (a paid invoice can't be edited). An endpoint policy can't do it alone because the authorisation middleware runs before your code loads the record.

    • Write an AuthorizationHandler<TRequirement, TResource>, usually with OperationAuthorizationRequirement (Read, Update, Delete) so one handler holds every rule for a resource type: owner, team editor, viewer, admin.
    • In the endpoint, load the record, call IAuthorizationService.AuthorizeAsync(User, document, Operations.Update), and return Forbid(), or NotFound() when even confirming the record exists would disclose information.
    • For lists, filter in the database query; never load everything and check one by one.

    The trade-off: it's imperative, so a developer can forget the call. Back it with tests and query filters.

  2. When: Candidate mentions keeping the original file name Why: Checks path traversal when file names come from users
    How to answer

    It is a path traversal vulnerability. file=../../../etc/passwd resolves outside the reports folder, and file=/etc/passwd is worse: Path.Combine discards the base path when the second argument is rooted. The endpoint also has no authorisation and leaks whether files exist.

    Fix: do not let users name files. Map an ID to a stored path (database), or if names are required, take only Path.GetFileName(file), build the path, Path.GetFullPath it and check it starts with the root plus a separator, using the platform's case rules. Serve through PhysicalFileProvider or Results.File with the checked path, and add authorisation.

  3. When: Candidate mentions small files going through the API Why: Checks request size limits on endpoints that still accept bodies
    How to answer

    Set limits at every layer and fail fast with a clear status. Lower Kestrel's MaxRequestBodySize (default about 28.6 MB) globally, and per endpoint with [RequestSizeLimit]; requests over the limit get 413 Payload Too Large. Set FormOptions limits for multipart. Keep System.Text.Json's MaxDepth (64 by default; lower it for shallow contracts), so deeply nested JSON fails with 400. Validate collection counts in FluentValidation or data annotations and return a ValidationProblem. Stream large uploads instead of buffering, and add rate limiting (AddRateLimiter) so repeated large requests can't exhaust CPU and memory (a denial-of-service vector).

🛠 Real-world problems: how you handle them

Proxied uploads exhausted API memory and timed out large files
Situation
A [client document portal] for [300] accounting firms; ASP.NET Core API on [App Service, 4 instances] streaming uploads into Blob Storage; files up to [2 GB] at tax time.
Signals
API memory climbing to [3 GB] per instance, upload timeouts at [about 8%] for files over [500 MB], thread-pool queue length rising, and complaints in [October] peak.
Investigation
dotnet-counters showed working set and Gen2 growth during uploads; Application Insights showed long-running upload requests; a load test reproduced it with [50] concurrent 1 GB uploads.
Resolution
Immediate: raised request timeout and scaled out for the peak. Long term: direct uploads with create-only user delegation SAS and block blobs, a quarantine container scanned by Defender for Storage, and promote-on-clean; share links became revocable tokens.
Prevention
Load test with large files in the release pipeline, alerts on upload failure rate by size band, and a design rule that no endpoint accepts bodies over [10 MB].

How to tell it (STAR)

**S:** At [company] our document portal's uploads failed for large files during tax season, and API instances were running out of memory. **T:** I needed to make big uploads reliable without endlessly scaling the API. **A:** I confirmed with dotnet-counters and a load test that streaming files through Kestrel was the cause, then moved uploads to direct-to-blob with short-lived create-only SAS and block blobs, added a quarantine-and-scan step before files became downloadable, and replaced long-lived download links with revocable share tokens. **R:** Large-upload failures fell from [8%] to [under 1%], API memory dropped by [70%], and we reduced the instance count by [half].

More in Systems to Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me