Secure Browser-to-S3 Uploads, TypeScript Structural Typing, and Async React Effects

Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

Part 1: Direct Cloud Storage Uploads & IAM

A web service hosted on AWS lets signed-in customers send user-selected files straight from their web browser into an Amazon S3 bucket. The bucket itself must remain completely private, and long-lived AWS secret credentials must never reach browser code.

Describe the end-to-end upload flow you would build on AWS, and specify the exact IAM setup and permissions required on the backend service to support this design.

Part 2: TypeScript Type Checking & React Async Lifecycle

Inspect the TypeScript interface and React component below:

interface UserProfile {
  id: string;
  email: string;
  isAdmin: boolean;
}

function UserCard({ user }: { user: UserProfile }) {
  return <div>{user.email}</div>;
}
  1. Contrast TypeScript's structural type system with nominal type systems such as Java's, and explain what that difference means in practice when callers pass objects into UserCard.
  2. Suppose a component loads user records asynchronously inside useEffect. What bugs—around stale UI updates, request races, or retained resources—occur if the component unmounts or re-runs the effect while the network call is still in flight? Show a clean React pattern that prevents them.

Scope & Expectations

  • Walk through a credential-free browser upload architecture using temporary signed S3 upload grants, paired with least-privilege IAM role policies and required bucket settings (such as public-access blocks and CORS).
  • Demonstrate with concrete examples how shape-based structural compatibility differs from explicit implements declarations—including excess-property checks on inline literals and runtime type erasure.
  • Explain why out-of-order responses and post-unmount work happen inside useEffect, and provide a complete cancellation cleanup implementation.

Step-by-step walkthrough

  1. Map out the three questions

    This technical screen covers three practical full-stack engineering topics. Address each part directly and concretely:

    1. Cloud security (AWS S3 + IAM): enable client-side browser uploads straight into a private S3 bucket using short-lived presigned URLs (or presigned POST policies) generated by an application server running under a minimal IAM role.
    2. TypeScript vs Java type systems: contrast TypeScript's shape-based structural typing with Java's name-based nominal typing, and show what passes or fails when calling <UserCard user={...} />.
    3. React useEffect async lifecycle: explain out-of-order network race conditions and post-unmount resource retention, and fix both cleanly with AbortController.
  2. Part 1: how presigned S3 uploads work without exposing keys

    Amazon S3 (Simple Storage Service) stores files ("objects") inside private containers ("buckets"), and AWS IAM (Identity and Access Management) controls which identities may perform which actions on which AWS resources.

    Why the two naive upload designs fail:

    • Putting AWS access keys in browser code is unsafe: anything shipped to the browser can be extracted from DevTools by any visitor.
    • Making the bucket public is unsafe, and proxying files through your backend is wasteful: public write access lets anyone on the internet upload arbitrary content at your expense, while streaming 50 MB uploads through your web server ties up backend RAM, CPU, and network bandwidth.

    The standard AWS solution is a presigned URL (or presigned POST): a temporary upload ticket cryptographically signed locally by your backend server using its IAM role credentials. Signing requires zero network calls to S3 — S3 verifies the signature later when the browser uploads the file directly:

    Browser                        App Server (IAM Role)                 Private S3 Bucket
      │                                     │                                    │
      │ 1. POST /api/uploads                │                                    │
      │    {contentType: "image/png",       │                                    │
      │     sizeBytes: 2097152}             │                                    │
      │────────────────────────────────────►│ 2. Verify logged-in user & type    │
      │                                     │    Generate key uploads/u_42/<uuid>│
      │                                     │    Sign 300s POST policy (1B..10MB)│
      │◄────────────────────────────────────│ 3. Return {url, fields, key}       │
      │                                     │                                    │
      │ 4. POST multipart form + file bytes directly to S3 ─────────────────────►│
      │                                                                          │ Checks signature,
      │◄────────────────────────────────────────────────────── 204 No Content ───│ 300s expiry, size,
      │ 5. POST /api/uploads/complete {key} ►│ Record key & trigger virus scan   │ & server's IAM role
    

    Concrete numbers: if the server signs an upload at 12:00:00 with ExpiresIn = 300 (5 minutes) and a size range of 1 byte to 10 MiB (10,485,760 bytes), S3 rejects the ticket at 12:05:01, rejects a 12 MiB file, and rejects any attempt to upload to a different key.

    • Presigned POST vs presigned PUT: a presigned POST attaches a signed policy document in form fields that lets S3 enforce a byte range (["content-length-range", 1, 10485760]). A presigned PUT returns a single signed URL where the browser sends raw bytes in the PUT body; it is even simpler when an exact Content-Type (and optionally an exact pre-declared Content-Length) is sufficient.
  3. Part 1: server signing code and browser upload call

    Never let the browser pick the S3 object key, or a malicious client could overwrite another user's file or write outside the uploads/ folder. Instead, the server builds uploads/<user_id>/<uuid> after authenticating the user and checking the MIME type:

    import uuid
    import boto3
    
    BUCKET_NAME = "example-user-uploads"
    ALLOWED_CONTENT_TYPES = {"image/png", "image/jpeg", "application/pdf"}
    MAX_UPLOAD_BYTES = 10 * 1024 * 1024  # 10 MiB = 10,485,760 bytes
    
    # No hardcoded keys: boto3 automatically reads temporary credentials from the server's IAM role
    s3_client = boto3.client("s3")
    
    
    def create_presigned_upload(user_id: str, content_type: str) -> dict:
        """Return a 5-minute presigned S3 POST ticket scoped to one server-chosen object key."""
        if content_type not in ALLOWED_CONTENT_TYPES:
            raise ValueError(f"Unsupported file type: {content_type}")
    
        object_key = f"uploads/{user_id}/{uuid.uuid4()}"
    
        # Conditions enforce exact Content-Type and a 1 B .. 10 MiB byte limit at S3
        presigned = s3_client.generate_presigned_post(
            Bucket=BUCKET_NAME,
            Key=object_key,
            Fields={"Content-Type": content_type},
            Conditions=[
                {"Content-Type": content_type},
                ["content-length-range", 1, MAX_UPLOAD_BYTES],
            ],
            ExpiresIn=300,
        )
        return {"key": object_key, "url": presigned["url"], "fields": presigned["fields"]}
    

    On the frontend, the browser requests the signed fields from /api/uploads and submits a multipart/form-data POST directly to S3 (with "file" appended last, as S3 requires):

    async function uploadFileToS3(file: File): Promise<string> {
      const ticketRes = await fetch("/api/uploads", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ contentType: file.type, sizeBytes: file.size }),
      });
      if (!ticketRes.ok) throw new Error(`Ticket request failed: ${ticketRes.status}`);
    
      const { url, fields, key } = await ticketRes.json();
      const form = new FormData();
      for (const [name, value] of Object.entries(fields)) {
        form.append(name, String(value));
      }
      form.append("file", file); // S3 ignores any form fields placed after the file
    
      const uploadRes = await fetch(url, { method: "POST", body: form });
      if (!uploadRes.ok) throw new Error(`S3 upload failed: ${uploadRes.status}`);
      return key;
    }
    
  4. Part 1: exact IAM role policy and S3 bucket configuration

    1. Attach an IAM Role to the compute service (never static access keys). Run your backend with an IAM role — an EC2 instance profile, ECS task role, or Lambda execution role. AWS Security Token Service (STS) rotates short-lived credentials automatically in the background, so there are no static AWS_SECRET_ACCESS_KEY values to leak.

    2. Scope the server role's IAM policy to s3:PutObject on uploads/* only. Because a presigned request inherits at most the permissions of the IAM principal that signed it, restricting the role restricts both the server and every presigned URL it ever issues:

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "AllowDirectUploadsToPrefixOnly",
          "Effect": "Allow",
          "Action": ["s3:PutObject"],
          "Resource": "arn:aws:s3:::example-user-uploads/uploads/*"
        }
      ]
    }
    

    If the bucket encrypts objects using a customer-managed AWS KMS (Key Management Service) key (SSE-KMS) rather than S3's default SSE-S3 encryption, also grant kms:GenerateDataKey (and kms:Decrypt if using multipart uploads) on that specific KMS key ARN.

    3. Lock down the S3 bucket settings and enable CORS. - Keep S3 Block Public Access turned ON (all four toggles) and set Object Ownership to Bucket owner enforced (disabling legacy ACLs). - Enforce HTTPS-only requests via a bucket policy denying aws:SecureTransport == false. - Configure CORS (Cross-Origin Resource Sharing) — browser security rules that permit JavaScript served from https://app.example.com to make cross-origin POST/PUT calls to https://example-user-uploads.s3.amazonaws.com:

    [
      {
        "AllowedOrigins": ["https://app.example.com"],
        "AllowedMethods": ["POST", "PUT"],
        "AllowedHeaders": ["Content-Type"],
        "MaxAgeSeconds": 3000
      }
    ]
    
  5. Part 2.1: structural typing in TypeScript vs nominal typing in Java

    Type systems decide whether a value of type A can be passed to a function expecting type B in one of two ways:

    • Nominal typing (Java, C#, C++): compatibility is decided by explicitly declared names and inheritance (class Employee implements UserProfile). Even if two types have the exact same fields and types, they are incompatible unless one explicitly declares that it implements or extends the other.
    • Structural typing (TypeScript): compatibility is decided by shape — whether the value has all required property names with compatible types. Type names and implements clauses are not required.

    Compare the exact same scenario in TypeScript and Java:

    interface UserProfile {
      id: string;
      email: string;
      isAdmin: boolean;
    }
    
    function UserCard({ user }: { user: UserProfile }) {
      return <div>{user.email}</div>;
    }
    
    // Employee never writes "implements UserProfile", and also has an extra field "department"
    class Employee {
      constructor(
        public id: string,
        public email: string,
        public isAdmin: boolean,
        public department: string,
      ) {}
    }
    
    const alice = new Employee("u_1", "alice@example.com", false, "avionics");
    const element = <UserCard user={alice} />; // Compiles cleanly in TypeScript!
    
    interface UserProfile { String id(); String email(); boolean isAdmin(); }
    record Employee(String id, String email, boolean isAdmin, String department) {}
    
    // Compile-time error in Java!
    // Even though Employee has id(), email(), and isAdmin(), it did not declare "implements UserProfile".
    
  6. Part 2.1: practical consequences when passing objects into UserCard

    Structural typing shapes day-to-day React + TypeScript code in four concrete ways:

    1. Easy composition across layers: an AdminAccount, a GraphQL query result, or a test mock with { id: "1", email: "a@b.com", isAdmin: true, lastLogin: "2026-05-01" } stored in a variable can be passed straight into <UserCard user={account} /> without adapter classes.
    2. Fresh object literals trigger TypeScript's "excess property check": if you write an inline object literal <UserCard user={{ id: "1", email: "a@b.com", isAdmin: false, depatment: "eng" }} />, TypeScript actually flags depatment as an error! Why? In an inline literal, an unknown property is almost always a typo (like isAdmn), whereas passing an existing variable const emp = { ... }; <UserCard user={emp} /> uses standard structural subtyping and succeeds.
    3. Accidental interchangeability of same-shaped primitives: type UserId = string and type OrderId = string have the exact same structure (string), so TypeScript lets you accidentally pass an OrderId where a UserId was expected unless you add a branded type (type UserId = string & { readonly __brand: "UserId" }).
    4. Zero runtime enforcement (type erasure): TypeScript strips all interfaces away when compiling to JavaScript. Writing const user = (await res.json()) as UserProfile checks nothing at runtime — if a broken backend sends {"id": "1", "email": "a@b.com", "isAdmin": "false"}, user.isAdmin is the non-empty string "false", which evaluates to true in if (user.isAdmin)!
  7. Part 2.2: what goes wrong when useEffect fetches data and unmounts

    Suppose a component fetches /api/users/${userId} inside useEffect and calls setUser(data) when the response arrives. Three distinct bugs arise when the user navigates away or switches userId rapidly:

    Time     Action / Network Event                               UI State (WITHOUT cleanup)
    -------  ---------------------------------------------------  ------------------------------------
    t=0 ms   User opens userId="1" -> Request A starts (slow)     Loading...
    t=50 ms  User clicks userId="2" -> Request B starts (fast)    Loading...
    t=200 ms Request B ("2") finishes -> setUser(user2)           Shows User 2 (correct)
    t=800 ms Request A ("1") finishes late -> setUser(user1)!!    Shows User 1 under User 2's URL! (BUG)
    
    1. Out-of-order race conditions (the #1 real-world bug): as shown above, network latency varies per request; without cancelling or ignoring the superseded effect run, a slow earlier response overwrites a faster newer response with stale data.
    2. Wasted work and retained memory after unmount: if the component unmounts at t = 50 ms while downloading a large payload, an uncancelled fetch keeps consuming bandwidth/CPU and keeps its callback closures in memory until the promise settles. (Note: React 18 removed the old "Can't perform a React state update on an unmounted component" console warning for plain promises, because true permanent memory leaks come from uncleaned intervals, addEventListener handlers, or WebSocket subscriptions that never settle unless removed in cleanup.)
    3. Async callback trap: writing useEffect(async () => { ... }, [userId]) is a bug because an async function implicitly returns a Promise, whereas React requires useEffect to return either undefined or a synchronous cleanup function () => void.
  8. Part 2.2: solving races and unmount cleanup with AbortController

    AbortController is the built-in Web API for cancelling in-flight fetch calls: passing { signal: controller.signal } into fetch aborts the HTTP request immediately when controller.abort() runs in useEffect's cleanup function.

    import { useEffect, useState } from "react";
    
    function useUserProfile(userId: string) {
      const [user, setUser] = useState<UserProfile | null>(null);
      const [loading, setLoading] = useState<boolean>(true);
      const [error, setError] = useState<Error | null>(null);
    
      useEffect(() => {
        // Fresh controller scoped to THIS specific effect run (this userId)
        const controller = new AbortController();
        setLoading(true);
        setError(null); // Clear any error left over from a previous userId
    
        async function fetchUser() {
          try {
            const res = await fetch(`/api/users/${encodeURIComponent(userId)}`, {
              signal: controller.signal,
            });
            if (!res.ok) {
              throw new Error(`Request failed with status ${res.status}`);
            }
            const data: UserProfile = await res.json();
            if (!controller.signal.aborted) {
              setUser(data);
              setLoading(false);
            }
          } catch (err) {
            // Ignore AbortError because we cancelled this outdated/unmounted request intentionally
            if (controller.signal.aborted) return;
            setError(err instanceof Error ? err : new Error(String(err)));
            setLoading(false);
          }
        }
    
        fetchUser();
    
        // React runs this cleanup BOTH on unmount AND right before re-running when userId changes
        return () => {
          controller.abort();
        };
      }, [userId]);
    
      return { user, loading, error };
    }
    

    Why this pattern handles every edge case:

    • Component unmounts mid-flight: React calls controller.abort(), cancelling the underlying browser network request and skipping setUser / setError.
    • userId changes from "1" to "2": React runs the cleanup of effect "1" before starting effect "2", aborting Request A so it can never overwrite Request B.
    • React <StrictMode> double-invocation in development: StrictMode intentionally runs mount -> cleanup -> mount to surface missing cleanups; with controller.abort(), the first simulated mount cancels cleanly. (For third-party promise SDKs that do not accept an AbortSignal, pair the same structure with a local boolean let cancelled = false; return () => { cancelled = true; };.)

Intuition & how it works

All three parts of this question revolve around enforcing explicit, trustworthy boundaries across a modern web stack: - A presigned S3 URL works like a hotel front desk encoding a guest keycard that opens only Room 402 for the next 5 minutes: the browser never touches the master AWS secret key, the bucket stays completely private, and multi-megabyte uploads go straight to S3 instead of clogging your app server. - Structural typing in TypeScript works like checking whether a visitor's badge displays id, email, and isAdmin (shape), whereas nominal typing in Java checks whether the badge was explicitly issued under the title implements UserProfile (declared name). - useEffect cleanup with AbortController works like cancelling a food delivery when you move apartments so a delayed driver from your old order never overwrites what is on the table now.

Without these boundaries, common shortcuts fail badly in production. Putting AWS keys in frontend code exposes them to anyone opening browser DevTools, while making an S3 bucket public lets strangers upload gigabytes on your bill. On the frontend, trusting res.json() as UserProfile does zero runtime validation because TypeScript types vanish when compiled to JavaScript, and firing fetch inside useEffect without an abort cleanup lets slow, stale responses overwrite fresher screen state.

Walk through a concrete timeline: a user uploads a 2 MiB avatar (ExpiresIn = 300 seconds) to server-generated key uploads/u_7/9f1c..., which S3 accepts because the server's IAM role allows s3:PutObject on uploads/*. Next, the user clicks from profile u_7 (800 ms API latency) to u_8 (200 ms API latency) at t = 50 ms: React immediately runs u_7's useEffect cleanup (controller.abort()), cancelling the 800 ms request so only u_8's 200 ms response ever updates UserCard.

Key points

  • Presigned URLs / Presigned POSTs delegate one narrow S3 upload without exposing secrets. Your backend authenticates the user, chooses a safe key (uploads/<userId>/<uuid>), and locally signs a short-lived policy (ExpiresIn = 300 seconds, plus content-length-range on a presigned POST) using temporary credentials from its IAM role (an AWS identity attached directly to an EC2 instance, ECS task, or Lambda function without static secret keys).
  • Lock down both the IAM role and the S3 bucket. Grant the server's IAM role only s3:PutObject on arn:aws:s3:::<bucket>/uploads/* (plus kms:GenerateDataKey if using a customer-managed AWS KMS encryption key), keep S3 Block Public Access enabled, enforce HTTPS, and add CORS (Cross-Origin Resource Sharing) rules so browsers allow cross-origin POST/PUT uploads from your frontend domain.
  • TypeScript uses structural typing; Java uses nominal typing. In TypeScript, any variable whose type includes { id: string; email: string; isAdmin: boolean } (even an Employee class with extra properties and no implements clause) can be passed to UserCard; only fresh inline object literals trigger an extra "excess property check" to catch typos.
  • TypeScript types are erased at runtime. Type assertions like data as UserProfile vanish in compiled JavaScript and never inspect live API payloads.
  • Every useEffect that starts async work must return a cleanup function. Passing { signal: controller.signal } from an AbortController (browser cancellation API for fetch) and calling controller.abort() in the cleanup cancels in-flight downloads on unmount and prevents out-of-order race conditions when dependencies like userId change.

Common mistakes

  • Shipping AWS access keys to the browser or granting s3:* on * to the server role: frontend secrets are publicly readable in the bundle/network tab, and over-broad server roles turn a server compromise into full-account data loss.
  • Letting the browser choose the S3 object key or setting multi-day presigned expiries: client-chosen keys allow overwriting another user's uploads or escaping uploads/; generate a server-side UUID key and mint fresh 5-minute URLs per upload attempt instead.
  • Forgetting S3 CORS headers: direct browser-to-S3 fetch calls are cross-origin requests and fail in the browser with opaque CORS errors even when the IAM signature is completely valid.
  • Assuming structural typing rejects extra fields everywhere — or validates API JSON: variables with extra properties pass into UserCard cleanly, and as UserProfile lets malformed JSON like {"isAdmin": "false"} (a truthy string!) slip right into React state.
  • Writing useEffect(async () => { ... }) or using a single component-wide isMounted ref: an async callback returns a Promise instead of a cleanup function, and a component-wide isMounted boolean only detects final unmount — it completely misses race conditions when userId changes while the component stays mounted!

Follow-up questions

  • How can you validate incoming JSON payloads at runtime when external endpoints might violate your TypeScript interfaces? Treat await res.json() as unknown at the network boundary and pass it through a runtime schema validator (a library such as Zod or Valibot that checks property names and value types in JavaScript at runtime and derives the static TypeScript type from the same schema). If isAdmin arrives as "false" instead of a boolean or email is missing, UserProfileSchema.safeParse(data) fails immediately with a descriptive error before bad data ever enters React state. You can also write a custom type guard function (function isUserProfile(x: unknown): x is UserProfile) when you want zero external dependencies.
  • Which AWS capabilities reduce upload latency and improve resilience when clients send large files from around the globe? Enable S3 Transfer Acceleration (which accepts uploads at the nearest global Amazon CloudFront edge location and routes them over AWS's private backbone network to the bucket) or place regional buckets close to users via S3 Multi-Region Access Points paired with Cross-Region Replication (CRR) for async durability across regions. For files larger than ~50–100 MB, switch to S3 Multipart Upload (splitting a file into smaller chunks uploaded in parallel with presigned part URLs), so a brief network drop retries one 10 MB chunk instead of restarting the entire file — just remember to expose the ETag header in S3 CORS so the browser can return part ETags on completion.
  • How do you apply least-privilege design to the backend IAM permissions and upload constraints for this S3 workflow? Least privilege means granting only the exact actions, resources, principals, and time windows required for a single job — and nothing more. Here, the upload-signing service gets its own dedicated IAM role with only s3:PutObject (no s3:GetObject, s3:DeleteObject, or s3:ListBucket) scoped strictly to arn:aws:s3:::example-user-uploads/uploads/*, while separate reader or virus-scanner workers use separate roles. Combined with server-generated uploads/<userId>/<uuid> keys, ExpiresIn = 300 seconds, and byte-range conditions in the presigned policy, even a leaked presigned ticket or compromised upload container cannot read, list, or delete existing user files.

Follow-up questions

Similar questions

More Boeing interview questions

All 2 Boeing questions →