Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: 8+ Years (Senior & Lead)

Expert Core Java

  • Tricky Java Output, Operators & OOP Edge Cases — Interview Questions
  • Tricky Exceptions, Memory & Keyword Questions — Interview Questions
  • Classic Java Language Questions, Senior-Grade Answers — Interview Questions
  • Classic Collections, Threads & JDK APIs, Senior-Grade Answers — Interview Questions
  • Reflection, Dynamic Proxies, final & Modern OOP Design — Interview Questions

JVM Internals & Performance

  • Class Loading, Bytecode & Object Layout — Interview Questions
  • JIT Compilation & Runtime Optimisations — Interview Questions
  • Garbage Collectors Deep Dive — Interview Questions
  • JVM Tuning, GC Logs & Memory Footprint — Interview Questions
  • Memory Leaks, OutOfMemoryErrors & Profiling Tools — Interview Questions
  • Modules, Agents & Advanced JVM APIs — Interview Questions

Collections & Concurrency at Scale

  • Collections Internals & Complexity — Interview Questions
  • Iterators, Comparators & Ordering Contracts — Interview Questions
  • Concurrent Collections, Queues & Lock-Free Structures — Interview Questions
  • Threads, Executors & ForkJoin Internals — Interview Questions
  • Locks, Atomics, CAS & Synchronizers — Interview Questions
  • Java Memory Model, volatile, Fences & ThreadLocal — Interview Questions
  • Deadlock, Livelock, Starvation & Concurrent Design — Interview Questions
  • CompletableFuture, Parallel Streams & Non-Blocking I/O — Interview Questions

Modern Java (8 to 21+)

  • Lambdas & Functional Interfaces Internals — Interview Questions
  • Streams & Collectors Deep Dive — Interview Questions
  • Optional & Interface Default/Static Methods — Interview Questions
  • Java 9–25 Features & Virtual Threads — Interview Questions

Design Patterns, SOLID & Clean Code

  • Design Pattern Trade-offs & Combinations — Interview Questions
  • SOLID, Clean Code & Anti-Patterns — Interview Questions

Spring & Spring Boot Internals

  • IoC, Dependency Injection & Bean Lifecycle Internals — Interview Questions
  • Spring AOP, Proxies & @Async Internals — Interview Questions
  • Spring Configuration, Auto-Configuration & Custom Starters — Interview Questions
  • Spring MVC & REST Internals, Exception Frameworks — Interview Questions
  • Spring Security Advanced Internals — Interview Questions
  • Spring WebFlux, Reactor & R2DBC — Interview Questions
  • Spring Cloud, Observability & Distributed Tracing — Interview Questions
  • Spring Boot 3, Native Images & Production Scenarios — Interview Questions

JPA, Hibernate & Databases at Scale

  • Spring Data JPA — Queries, Projections, Custom Repositories & Locking — Interview Questions
  • JPA Entity Mapping, Associations & Cascades — Interview Questions
  • JPQL vs Native Queries in Depth — Interview Questions
  • Hibernate Caching — First-Level, Second-Level & Query Cache — Interview Questions
  • Lazy vs Eager Loading, LazyInitializationException & N+1 — Interview Questions
  • JPA Transactions, Propagation, Isolation & Dirty Checking — Interview Questions
  • SQL vs NoSQL, Indexing & Query Tuning — Interview Questions
  • Database Scaling, Replication, Pooling & Consistency Models — Interview Questions
  • Redis, Search, Time-Series, CDC & Transactional Data Modelling — Interview Questions

Testing Strategy & API Design

  • Spring Boot Test Slices, Context & Test Strategy — Interview Questions
  • Testing Web, Persistence, Security, Async & Messaging in Spring Boot — Interview Questions
  • JUnit 5 & Mockito, Advanced — Interview Questions
  • MockMvc, WebTestClient & Testcontainers in Depth — Interview Questions
  • REST Principles, Status Codes & Resource Design — Interview Questions
  • OpenAPI, Validation Errors, API Versioning & GraphQL — Interview Questions

Build, DevOps & Cloud

  • Maven & Gradle at Scale — Interview Questions
  • Git, CI/CD Pipelines & Release Safety — Interview Questions
  • Docker & Kubernetes for Java Engineers — Interview Questions
  • Quality Gates, Artifact Repositories & Secrets Management — Interview Questions
  • AWS Deployment & Scaling for Spring Boot — Interview Questions
  • Multi-Cloud Deployment, High Availability, Cost & Cloud Troubleshooting — Interview Questions

Kafka & Messaging

  • Kafka Internals & Delivery Semantics — Interview Questions
  • Spring Kafka — Error Handling, DLQs, Schemas & Operations — Interview Questions
  • RabbitMQ, JMS & Messaging Models — Interview Questions

Microservices & Architecture

  • Distributed Systems Fundamentals — CAP, Consistency, Availability & SLOs — Interview Questions
  • DDD, Hexagonal Architecture & Service Boundaries — Interview Questions
  • Event-Driven Architecture, CQRS, Event Sourcing, Sharding & Idempotency — Interview Questions
  • Rate Limiting, Resilience, Caching at Scale & Chaos Engineering — Interview Questions
  • Files, Documents & Internationalisation in Java Backends — Interview Questions
  • WebSockets, Schedulers, Notifications & Real-Time Pipelines — Interview Questions

System Design Scenarios

  • Booking Systems, CRS, Inventory & Concurrency Control — Interview Questions
  • Dynamic Pricing & Rule Engines — Interview Questions
  • Partner Integrations — OTA Sync, Retries, Webhooks, Reconciliation & Bulk Data — Interview Questions
  • Designing Caches & Rate Limiters — Interview Questions
  • Event-Driven Architecture, Kafka at Scale, IoT & Real-Time Pipelines — Interview Questions
  • Observability, Logging, Alerting & Audit Systems — Interview Questions
  • Multi-Tenant SaaS, Identity & Platform Services — Interview Questions
  • Search, Notifications, Chat, Fraud Detection & Workflows — Interview Questions
  • Extreme Scale, 99.99% Availability, DR & Project Deep-Dive Stories — Interview Questions

Security for Senior Engineers

  • Tokens, OAuth2 PKCE, Web Attacks & API Security — Interview Questions
  • TLS, mTLS, Zero Trust, Secrets, DDoS & Privacy Compliance — Interview Questions

Leadership & Behavioural

  • Leadership Style, Motivation & Team Health — Interview Questions
  • Delivery, Planning & Decisions Under Uncertainty — Interview Questions
  • Problem Solving, Growth & Career Stories — Interview Questions
  • Stakeholder Communication, Ethics & Compliance — Interview Questions
  • Mentoring, Knowledge Sharing & Code Reviews — Interview Questions
  • Agile & Scrum Practices for Senior Engineers — Interview Questions
  • Architecture Decision-Making — Interview Questions
  • Conflict Resolution & Difficult Conversations — Interview Questions
Chaturmind
← Java Interview Prep: 8+ Years (Senior & Lead)

Expert Core Java

  • Tricky Java Output, Operators & OOP Edge Cases — Interview Questions
  • Tricky Exceptions, Memory & Keyword Questions — Interview Questions
  • Classic Java Language Questions, Senior-Grade Answers — Interview Questions
  • Classic Collections, Threads & JDK APIs, Senior-Grade Answers — Interview Questions
  • Reflection, Dynamic Proxies, final & Modern OOP Design — Interview Questions

JVM Internals & Performance

  • Class Loading, Bytecode & Object Layout — Interview Questions
  • JIT Compilation & Runtime Optimisations — Interview Questions
  • Garbage Collectors Deep Dive — Interview Questions
  • JVM Tuning, GC Logs & Memory Footprint — Interview Questions
  • Memory Leaks, OutOfMemoryErrors & Profiling Tools — Interview Questions
  • Modules, Agents & Advanced JVM APIs — Interview Questions

Collections & Concurrency at Scale

  • Collections Internals & Complexity — Interview Questions
  • Iterators, Comparators & Ordering Contracts — Interview Questions
  • Concurrent Collections, Queues & Lock-Free Structures — Interview Questions
  • Threads, Executors & ForkJoin Internals — Interview Questions
  • Locks, Atomics, CAS & Synchronizers — Interview Questions
  • Java Memory Model, volatile, Fences & ThreadLocal — Interview Questions
  • Deadlock, Livelock, Starvation & Concurrent Design — Interview Questions
  • CompletableFuture, Parallel Streams & Non-Blocking I/O — Interview Questions

Modern Java (8 to 21+)

  • Lambdas & Functional Interfaces Internals — Interview Questions
  • Streams & Collectors Deep Dive — Interview Questions
  • Optional & Interface Default/Static Methods — Interview Questions
  • Java 9–25 Features & Virtual Threads — Interview Questions

Design Patterns, SOLID & Clean Code

  • Design Pattern Trade-offs & Combinations — Interview Questions
  • SOLID, Clean Code & Anti-Patterns — Interview Questions

Spring & Spring Boot Internals

  • IoC, Dependency Injection & Bean Lifecycle Internals — Interview Questions
  • Spring AOP, Proxies & @Async Internals — Interview Questions
  • Spring Configuration, Auto-Configuration & Custom Starters — Interview Questions
  • Spring MVC & REST Internals, Exception Frameworks — Interview Questions
  • Spring Security Advanced Internals — Interview Questions
  • Spring WebFlux, Reactor & R2DBC — Interview Questions
  • Spring Cloud, Observability & Distributed Tracing — Interview Questions
  • Spring Boot 3, Native Images & Production Scenarios — Interview Questions

JPA, Hibernate & Databases at Scale

  • Spring Data JPA — Queries, Projections, Custom Repositories & Locking — Interview Questions
  • JPA Entity Mapping, Associations & Cascades — Interview Questions
  • JPQL vs Native Queries in Depth — Interview Questions
  • Hibernate Caching — First-Level, Second-Level & Query Cache — Interview Questions
  • Lazy vs Eager Loading, LazyInitializationException & N+1 — Interview Questions
  • JPA Transactions, Propagation, Isolation & Dirty Checking — Interview Questions
  • SQL vs NoSQL, Indexing & Query Tuning — Interview Questions
  • Database Scaling, Replication, Pooling & Consistency Models — Interview Questions
  • Redis, Search, Time-Series, CDC & Transactional Data Modelling — Interview Questions

Testing Strategy & API Design

  • Spring Boot Test Slices, Context & Test Strategy — Interview Questions
  • Testing Web, Persistence, Security, Async & Messaging in Spring Boot — Interview Questions
  • JUnit 5 & Mockito, Advanced — Interview Questions
  • MockMvc, WebTestClient & Testcontainers in Depth — Interview Questions
  • REST Principles, Status Codes & Resource Design — Interview Questions
  • OpenAPI, Validation Errors, API Versioning & GraphQL — Interview Questions

Build, DevOps & Cloud

  • Maven & Gradle at Scale — Interview Questions
  • Git, CI/CD Pipelines & Release Safety — Interview Questions
  • Docker & Kubernetes for Java Engineers — Interview Questions
  • Quality Gates, Artifact Repositories & Secrets Management — Interview Questions
  • AWS Deployment & Scaling for Spring Boot — Interview Questions
  • Multi-Cloud Deployment, High Availability, Cost & Cloud Troubleshooting — Interview Questions

Kafka & Messaging

  • Kafka Internals & Delivery Semantics — Interview Questions
  • Spring Kafka — Error Handling, DLQs, Schemas & Operations — Interview Questions
  • RabbitMQ, JMS & Messaging Models — Interview Questions

Microservices & Architecture

  • Distributed Systems Fundamentals — CAP, Consistency, Availability & SLOs — Interview Questions
  • DDD, Hexagonal Architecture & Service Boundaries — Interview Questions
  • Event-Driven Architecture, CQRS, Event Sourcing, Sharding & Idempotency — Interview Questions
  • Rate Limiting, Resilience, Caching at Scale & Chaos Engineering — Interview Questions
  • Files, Documents & Internationalisation in Java Backends — Interview Questions
  • WebSockets, Schedulers, Notifications & Real-Time Pipelines — Interview Questions

System Design Scenarios

  • Booking Systems, CRS, Inventory & Concurrency Control — Interview Questions
  • Dynamic Pricing & Rule Engines — Interview Questions
  • Partner Integrations — OTA Sync, Retries, Webhooks, Reconciliation & Bulk Data — Interview Questions
  • Designing Caches & Rate Limiters — Interview Questions
  • Event-Driven Architecture, Kafka at Scale, IoT & Real-Time Pipelines — Interview Questions
  • Observability, Logging, Alerting & Audit Systems — Interview Questions
  • Multi-Tenant SaaS, Identity & Platform Services — Interview Questions
  • Search, Notifications, Chat, Fraud Detection & Workflows — Interview Questions
  • Extreme Scale, 99.99% Availability, DR & Project Deep-Dive Stories — Interview Questions

Security for Senior Engineers

  • Tokens, OAuth2 PKCE, Web Attacks & API Security — Interview Questions
  • TLS, mTLS, Zero Trust, Secrets, DDoS & Privacy Compliance — Interview Questions

Leadership & Behavioural

  • Leadership Style, Motivation & Team Health — Interview Questions
  • Delivery, Planning & Decisions Under Uncertainty — Interview Questions
  • Problem Solving, Growth & Career Stories — Interview Questions
  • Stakeholder Communication, Ethics & Compliance — Interview Questions
  • Mentoring, Knowledge Sharing & Code Reviews — Interview Questions
  • Agile & Scrum Practices for Senior Engineers — Interview Questions
  • Architecture Decision-Making — Interview Questions
  • Conflict Resolution & Difficult Conversations — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 8+ Years (Senior & Lead)Microservices & Architecture
✓ FreeAdvanced· 12 min read

Files, Documents & Internationalisation in Java Backends — Interview Questions

Switching locales dynamically, using message bundles well, testing i18n and fixing encoding issues; generating PDFs (iText/PDFBox/OpenPDF) and Excel (Apache POI SXSSF), testing file generation and running it in CI/CD; secure file uploads, streaming large uploads, resumable uploads and downloads, correct MIME types, encrypting stored files, deduplicating files at scale, caching binary downloads, and logging sensitive data safely.

Published September 25, 2026


How to use this lesson

These "everyday backend features" hide security and scalability traps:

  • path traversal and malware in uploads;
  • memory blow-ups from buffering files;
  • mojibake from wrong encodings;
  • personal data in logs.

Answer with streaming, validation, and defence in depth.

Q1. How do you switch locales dynamically in a web application?

Short answer: Spring resolves the locale per request through a LocaleResolver:

  • AcceptHeaderLocaleResolver (the browser's Accept-Language; the default, and stateless, which suits APIs);
  • CookieLocaleResolver/SessionLocaleResolver (a remembered user choice);
  • or a custom resolver (from the user's profile in the JWT, or from a query or header).

LocaleChangeInterceptor switches the locale when a request parameter is present (?lang=hi). Use LocaleContextHolder.getLocale() in services, and pass the locale explicitly to asynchronous tasks (it's thread-bound). For REST APIs: honour Accept-Language, return Content-Language, and let clients store their preference in the user profile.

Q2. How do you use message bundles effectively in multilingual applications?

Short answer:

  • MessageSource (Boot auto-configures spring.messages.basename=messages,validation), with messages.properties, messages_hi.properties and messages_fr_CA.properties. Fallback chain: fr_CA → fr → the default. Set spring.messages.fallback-to-system-locale=false to avoid surprises.
  • Keys, not sentences: use stable semantic keys (order.status.shipped), and parameterised messages with MessageFormat (order.confirmation=Order {0} will arrive on {1,date,long}). Don't concatenate translated fragments: word order differs between languages.
  • Plurals and gender: use ICU4J MessageFormat plural or select rules, for languages with complex plurals.
  • Validation messages from ValidationMessages.properties, with the locale-aware Bean Validation interpolator.
  • Encoding: properties files are UTF-8 by default since Java 9 (spring.messages.encoding=UTF-8).
  • Process: a translation-management workflow (Crowdin, Lokalise), CI checks for missing keys, and pseudo-localisation tests.
  • Formatting: dates, numbers and currency through the locale-aware APIs (DateTimeFormatter.ofLocalizedDate, NumberFormat.getCurrencyInstance(locale)), never hard-coded patterns.

Q3. How do you test internationalised content? How do you detect and fix encoding issues?

Short answer:

  • Testing:
    • unit-test the MessageSource for each supported locale (keys resolve, and there's no fallback to the default where a translation is expected);
    • completeness checks (every key in the default bundle exists in every language, as a build-time test);
    • MockMvc with Accept-Language headers, asserting the translated messages and the formatted dates and numbers;
    • pseudo-localisation ([!!! Ŝéàřçĥ !!!]) to find hard-coded strings and truncation;
    • right-to-left layout checks in the UI;
    • round-trip tests with non-ASCII data (Devanagari, emoji, accented characters) through the whole stack: the API, the database and exports.
  • Encoding issues (mojibake like é, ?, or broken emoji):
    • enforce UTF-8 end to end:
      • source files and the build (project.build.sourceEncoding=UTF-8);
      • the JVM default (UTF-8 by default since Java 18, JEP 400);
      • HTTP Content-Type: …; charset=UTF-8;
      • Spring server.servlet.encoding;
      • the database (UTF8MB4 in MySQL, not utf8/utf8mb3, which can't store emoji; UTF8 in Postgres);
      • the JDBC connection parameters;
      • file I/O with explicit charsets (Files.readString(path, UTF_8), never the default-charset FileReader on old JDKs);
      • CSV exports with a BOM when Excel needs it;
    • diagnose with hex dumps (find where the bytes changed), and check each hop's charset declaration.

Q4. How do you generate PDF files with iText or PDFBox?

Short answer:

  • The libraries:
    • OpenPDF (LGPL/MPL, an iText 4 fork);
    • iText 7/8 (AGPL or commercial: check the licence obligations before using it in a closed-source product);
    • Apache PDFBox (Apache 2.0; lower-level drawing, and great for reading and manipulating PDFs);
    • HTML-to-PDF with OpenHTMLtoPDF or Flying Saucer, fed by Thymeleaf templates, which designers can maintain (often the most maintainable option for invoices and reports).
  • Implementation tips:
    • stream the output (write directly to OutputStream, whether the HTTP response or S3 multipart), never build huge byte arrays;
    • embed fonts that support your languages (Devanagari needs proper shaping; iText pdfCalligraph, or HTML renderers with suitable fonts);
    • generate asynchronously for large reports (a job queue, then store in S3, then notify with a pre-signed link);
    • cache templates and fonts;
    • protect the documents where needed (encryption, digital signatures).

Q5. How do you export dynamic Excel files with Apache POI?

Short answer: Use Apache POI:

  • XSSFWorkbook (.xlsx) for small files;
  • SXSSFWorkbook (streaming) for large exports: it keeps only a window of rows in memory (for example 100), and flushes the rest to temporary files. Call dispose() afterwards.
  • Stream rows from the database (a JDBC cursor or JPA stream), rather than loading everything.
  • Reuse CellStyles, because creating a style per cell exhausts the workbook's limit (64,000 styles) and memory.
  • Write to the response or S3 as a stream. Set the headers (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, Content-Disposition: attachment; filename*=UTF-8''…).
  • Guard against CSV or formula injection: prefix cell values that start with =, +, - or @ coming from user input.
  • Alternatives: FastExcel or EasyExcel (faster and leaner for simple exports), or plain CSV when formatting isn't needed.

Q6. How do you write unit tests for file generation? How do you integrate PDF and Excel generation into CI/CD?

Short answer:

  • Separate content from rendering: build a view model (the data for the document) in testable code, and assert on it directly.
  • Parse the generated file back in tests:
    • PDFBox PDFTextStripper to assert the text content;
    • POI to read the cells, formulas and styles, and assert the values and the row counts.
  • Golden-file or snapshot tests: compare against approved outputs, carefully (normalise timestamps and IDs, or compare the extracted text instead of the bytes, because PDFs embed creation dates).
  • Edge cases: empty datasets, very large datasets (memory and time budgets), Unicode or right-to-left text, and special characters (formula injection).
  • In CI/CD:
    • run the tests headless (no GUI dependencies; bundle the fonts in the image or repository, so the rendering is consistent across machines);
    • add performance tests for big exports;
    • run licence scanning (the iText AGPL);
    • keep the template files versioned with the code;
    • archive sample outputs as build artifacts for manual review, when needed.

Q7. What's the best way to upload files securely in Spring Boot? How do you implement safe, resumable uploads?

Short answer:

  • Security:
    • authenticate and authorise the uploads;
    • enforce size limits (spring.servlet.multipart.max-file-size/max-request-size, plus the gateway limits);
    • validate the type by content (magic bytes: Apache Tika), not by extension or the client's Content-Type, against an allow-list;
    • never use the client's filename in paths (path traversal). Generate random storage keys, and keep the original name only as sanitised metadata;
    • scan for malware (ClamAV, or a cloud scanning service) before making files available;
    • store outside the web root, preferably in object storage;
    • serve downloads with Content-Disposition: attachment and X-Content-Type-Options: nosniff;
    • re-encode images (strip EXIF and embedded payloads);
    • add rate limits, and quotas per user.
  • Scalable and resumable uploads:
    • direct-to-object-storage uploads with pre-signed URLs, where the backend only issues URLs and records metadata;
    • S3 multipart uploads (parts of 5 MB to 5 GB, which can be retried individually, and resumed by listing the uploaded parts), or the tus protocol (an open resumable-upload standard, with Java server libraries);
    • checksums per part and for the whole object (integrity).
  • Workflow: upload → PENDING status → scan and validate asynchronously → AVAILABLE or REJECTED, with notifications.

Q8. How do you handle large file uploads with streaming?

Short answer: Never buffer entire files in memory:

  • with Servlet multipart, set spring.servlet.multipart.file-size-threshold (files above it go to temporary disk), and process MultipartFile.getInputStream() as a stream: pipe it to S3 (the SDK's multipart upload, or TransferManager with a stream) or a file channel;
  • for truly large files, bypass multipart parsing: stream the raw request body (HttpServletRequest.getInputStream(), or WebFlux Flux<DataBuffer> with DataBufferUtils.write), or better, pre-signed direct uploads to object storage;
  • enforce the size limits while streaming (count the bytes, and abort past the maximum);
  • compute checksums on the fly (DigestInputStream);
  • set the gateway, load balancer and server timeouts and body limits appropriately.

Q9. How do you serve file downloads with proper MIME types? How do you support large, resumable downloads?

Short answer:

  • MIME types: detect them with Files.probeContentType/Tika at upload time, and store the content type in the metadata. Serve with the correct Content-Type, Content-Disposition (attachment; filename*=UTF-8''<encoded> for non-ASCII names, or inline for previews), Content-Length, and X-Content-Type-Options: nosniff. Use application/octet-stream for unknown types.
  • Streaming: return ResponseEntity<Resource> (InputStreamResource, FileSystemResource) or StreamingResponseBody, so there's no full buffering.
  • Resumable downloads: support HTTP range requests (Accept-Ranges: bytes, with Range: bytes=… answered by 206 Partial Content and Content-Range). Spring MVC handles ranges automatically for Resource responses. Also give ETags or Last-Modified (with If-Range) so clients resume against the same version.
  • Best at scale: redirect to pre-signed URLs or a CDN (CloudFront signed URLs), letting S3 or the CDN handle ranges, bandwidth and caching.

Q10. How do you encrypt uploaded files in storage?

Short answer:

  • Server-side encryption in object storage:

    • S3 SSE-KMS (per-object data keys managed by KMS, with an access audit trail in CloudTrail, and key policies);
    • bucket default encryption;
    • GCS or Azure equivalents (CMEK).

    It's transparent to the application.

  • Client-side or envelope encryption, for extra sensitive data (or zero trust in the storage provider):

    1. generate a data key per file (KMS GenerateDataKey);
    2. encrypt the stream with AES-GCM (authenticated encryption; the AWS Encryption SDK, or Google Tink);
    3. store the encrypted data key alongside the object (in its metadata), and never store the plaintext key.
  • Key management: rotation (KMS automatic rotation, or re-wrapping the data keys), least-privilege decrypt permissions, per-tenant keys (BYOK) for multi-tenant isolation, and crypto-shredding (delete the key to make the data unrecoverable, which helps with GDPR erasure).

  • In transit: TLS everywhere.

Q11. How do you design file deduplication at scale?

Short answer:

  • Content addressing: compute a cryptographic hash (SHA-256) of the content while it streams. Store the blobs by hash (blobs/sha256/ab/cd/…), and keep a metadata table mapping the user's files to blob hashes, with reference counts.
  • On upload: if the hash already exists, skip storing the bytes (just add a reference). Clients can send the hash first ("do you have this?") to avoid uploading at all. This is source-side deduplication, with a security caveat: it can leak the existence of files across users, so scope it per tenant, or use convergent-encryption trade-offs.
  • Chunk-level deduplication (content-defined chunking with rolling hashes, like Rabin fingerprints) for large, similar files (backups, versioned documents). It saves much more space, but adds complexity.
  • Consistency: atomic reference-count updates, garbage collection of unreferenced blobs (a delayed, safe sweep), and integrity verification.
  • Scale: a sharded metadata store (a key-value store keyed by hash), and object storage for the blobs. Pre-filter with Bloom filters.

Q12. How do you cache binary file downloads?

Short answer:

  • A CDN in front of object storage (CloudFront, Cloud CDN): the best option, since it offloads bandwidth and latency globally. Use immutable, content-hashed URLs (/files/{sha256} or versioned paths), with Cache-Control: public, max-age=31536000, immutable. For private files, use signed URLs or cookies with short expiry, with the cache keyed without the signature where supported.
  • HTTP caching: ETag (the content hash) and Last-Modified, answering conditional requests (If-None-Match) with 304 Not Modified.
  • Application or proxy caches for generated files (thumbnails, reports): store the generated outputs in object storage (a cache by input hash), rather than regenerating them.
  • Don't cache large binaries in the JVM heap or in Redis (memory pressure). Use disk, object storage, or CDN caches instead.

Q13. How do you log sensitive data securely?

Short answer: Mostly by not logging it:

  • Classify the data (personal data, secrets, card data, health data). Never log passwords, tokens, API keys, full card numbers or CVVs (a PCI DSS violation), or full identity numbers.
  • Mask or tokenise at the source: a Logback masking converter or JSON provider (regex masking of card or email patterns), custom toString() on DTOs that excludes sensitive fields (records print everything by default), and Jackson @JsonIgnore or custom serialisers for log payloads.
  • Structured logging with allow-listed fields, rather than dumping whole request bodies. Turn off request body logging in HTTP client and server logging, or filter it.
  • Log IDs, not values (a user ID or hashed email, for correlation).
  • Protect the log pipeline: encryption in transit and at rest, access control on the log platform, retention limits, and region or residency compliance.
  • Audit logs (who accessed what) are separate from debug logs, and tamper-evident.
  • Verify: automated scans of logs for secrets or personal data patterns, and review logging in code reviews.

Follow-up questions this topic invites — and their answers

Q: Why use filename*=UTF-8''… in Content-Disposition? A: RFC 6266/5987 encoding lets browsers correctly display non-ASCII filenames (for example Hindi or accented characters). Include a plain ASCII filename= fallback for old clients.

Q: What is Apache Tika? A: A content-detection and extraction library. It identifies file types by magic bytes, and extracts text and metadata from PDFs, Office documents and more. It's useful for upload validation, search indexing and data-loss-prevention scanning.

Q: How do you prevent zip bombs and decompression attacks? A: Limit the decompressed size and ratio, and the number of entries, stream the extraction with counters, reject nested archives beyond a depth, and validate the entry names against path traversal ("zip slip").

Q: Should you store files in the database? A: Usually not. Object storage is cheaper, scales better, and supports CDNs and range requests. Keep the metadata (owner, hash, type, status) in the database, and the bytes in object storage. Small blobs in the database are acceptable when transactional coupling matters.

Previous

Rate Limiting, Resilience, Caching at Scale & Chaos Engineering — Interview Questions

Next

WebSockets, Schedulers, Notifications & Real-Time Pipelines — Interview Questions

AI Tutor

Lesson: Files, Documents & Internationalisation in Java Backends — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.