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.
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.
"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 /fileswith name, size and content type. The API checks permissions and reserves quota, creates a metadata row with statusUploading, 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 statusAvailable; 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."
| 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 |
| 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.
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)
| 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 |
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%].
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
Red flags
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.
c/w for upload, r for download), a short expiry and HTTPS only.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.
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.
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.
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.
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.
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.
S3 with presigned URLs and multipart upload, GuardDuty Malware Protection for S3, EventBridge, lifecycle to S3 Glacier, DynamoDB or RDS for metadata.
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 } } }
}
}]
}
UPDATE ... WHERE Used + Reserved + @size <= Quota, confirm on commit, release on expiry..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.POST /files, quotas, and WAF rules at Front Door.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.
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.
AuthorizationHandler<TRequirement, TResource>, usually with OperationAuthorizationRequirement (Read, Update, Delete) so one handler holds every rule for a resource type: owner, team editor, viewer, admin.IAuthorizationService.AuthorizeAsync(User, document, Operations.Update), and return Forbid(), or NotFound() when even confirming the record exists would disclose information.The trade-off: it's imperative, so a developer can forget the call. Back it with tests and query filters.
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.
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).
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].
Last updated 23 Nov 2026.