reader / case study
ENGINEERING CASE STUDY · PERSONAL PROJECT

How Reader works

Reader is a local-first Android e-reader for language learners. It turns selected words into AI-generated vocabulary cards, schedules reviews with FSRS, and supports offline dictionaries. A Spring Boot backend handles accounts and AI jobs, while a separate stateless worker calls AI providers. The same backend powers a web workspace for translating books, keeps every translated book in its own Git repository, and delivers vocabulary exercises through Telegram.

Kotlin · Jetpack Compose Java 21 · Spring Boot 4 PostgreSQL · Flyway Vue 3 SPA Git-backed versioning Docker · Hetzner VPS
Android app→ reader-server→ AI worker→ back to the device
SCROLL ↓
01 — The idea

Reading in a foreign language
and working with a dictionary

When reading in a foreign language, looking up an unknown word usually means switching to a separate dictionary, losing the context and returning to the text. Reader combines these steps in one workflow: the user selects a word, receives a card with a translation, pronunciation and examples of use, and the app schedules the next review.

Reading a bookEPUB · PDF · DjVu · FB2 · TXT
Selecting a worda single long press
Creating a cardtranslation · grammar · audio · video example
Review scheduling with FSRSspaced repetition, fully offline
Vocabulary accumulationthe data stays on the device
// The architecture is deliberately local-first — local storage is the primary store: books, reading positions, cards and review history are stored in Room on the device. The server receives only the data needed for explicit online features — a word and its sentence for an AI card, or a book uploaded by the user for translation. There is no cloud library, mandatory account synchronization or reader-behavior analytics.
02 — What the user sees

Core application features

The screenshots are from the Google Play build. Reading imported books, lookups in downloaded dictionaries and vocabulary reviews work offline. AI features and online catalogs require a network connection.

Library screen

Local library storage

The app imports EPUB, PDF, DjVu, FB2 and TXT through the system picker. Metadata and cover images are extracted locally; reading progress is saved for each book.

Android SAF · Room · persistable content:// permissions
Page carousel with bookmarks and notes

Page navigation, bookmarks and notes

A pull from the bottom edge opens a carousel of rendered page previews for moving quickly through the book. The same tools sheet contains bookmarks and notes; the progress slider scrolls the previews live and commits the new position on release.

page previews · bookmarks · notes · progress slider
Vocabulary card for the German verb lassen

Cards from selected words

Selecting a word opens its vocabulary card: translation, grammar notes, pronunciation audio and a video example of native speakers using the word.

AI cards · TTS · YouGlish integration · offline dictionary fallback
Selected-text translation

Selected-text translation

Selecting a sentence or paragraph opens a separate translation sheet. The fragment is translated with sentence context through the server-side AI pipeline; the result can be copied or saved as a vocabulary card.

/api/v1/ai/translate · sentence context · fingerprint cache
DE-EN dictionary lookup

Offline dictionaries

Dictionary packs are downloaded from the server once; subsequent lookups are local and do not require a network connection. Unresolved lookups are reported without context or user identity — only the word and language — so the packs can be improved.

Dict packs · /api/v1/dict · miss telemetry: word + language only
Study session

Review scheduling

Every card enters an FSRS review queue — source-to-target, target-to-source or mixed. The scheduler is implemented in Kotlin and runs entirely offline.

FSRS · Room review_states/logs · no sync required
OPDS catalog

Public-domain book catalogs

OPDS catalogs, including Project Gutenberg, can be browsed inside the app; a selected book is imported like a local file.

OPDS/Atom parser · streaming import
03 — From idea to system

From a reading app to a platform

Each component was added in response to a concrete requirement rather than to complicate the architecture.

STEP 01

A local reading application

Compose app, Room storage, format-specific reading engines, progress and bookmarks. No account required; guest mode remains available.

STEP 02

Controlling access to AI

Creating cards and translations incurs a cost for each model call. A Spring Boot backend was added for accounts, JWT sessions, entitlements and per-user rate limits; provider credentials are never stored in the app.

STEP 03

Moving model calls to a separate service

A shared service that does not store user state (plexus-ai) handles the integrations with AI providers. The backend implements its side of the job protocol: submission, claiming, events and retries.

STEP 04

A web workspace for book translation

A Vue workspace was added on the same backend: book upload, translation in chunks, a glossary and alignment review. Book translation uses a separate entitlement because it is significantly more resource-intensive.

STEP 05

Git-based translation versioning

Book translations use the same version-control mechanisms as source code. A standalone module represents every book as a Git repository: snapshots, branches, merges, suggestions and updates from the upstream project.

STEP 06

Telegram vocabulary exercises

A bot generates cloze and multiple-choice exercises from the user’s vocabulary-card history; free-form answers are evaluated by the same AI pipeline.

04 — System architecture

Three clients and one server-side application

The Android app and the translation SPA connect to the backend directly. Telegram users reach the bot through Telegram's Bot API, which the backend long-polls. The backend exposes two security boundaries: a public API protected by JWTs and entitlement checks, and an internal API reserved for trusted services.

Android
Reader app
Kotlin · Compose · Room
local-first
Browser
Translate SPA
Vue 3 · Vite
served by the backend
Telegram
Telegram users
bot chat · exercise links
reader-server · Spring Boot 4
/api/v1 — JWT + entitlements
auth · ai gateway · books · exercises · telegram · dicts · app/apk · admin
data
PostgreSQL 17
Flyway · ~30 migrations
pgvector-ready
inside the service
git-archive
bare Git repositories on disk
versioned books
reader-server · internal
/internal — X-Internal-Token
jobs/claim · jobs/{id}/events
constant-time compare · fail-closed
separate deployment
plexus-ai
stateless pull worker
stores provider credentials
separate deployment
plexus-mail
mail relay
verify · reset codes
external
Telegram API
long-poll bot
no webhook
external
AI providers
completions · embeddings · TTS

A dashed border marks components deployed separately from this repository. The app, SPA and bot use only the public API; the AI worker and mail relay use only the internal API.

05 — Inside the backend

One deployable application with internal boundaries

The monolith is a deliberate choice: it is inexpensive to operate and easier to reason about. The important boundaries are inside the application rather than between containers.

auth / user

public API
  • Email/password, Google and guest sign-in
  • JWT access (~15 min) + rotating refresh tokens
  • Email verification and password resets via plexus-mail
  • ALTCHA proof-of-work guard for anonymous mail endpoints (when enabled)
Verification codes stored as sha256(code:userId) — never plaintext. Refresh-token rotation prevents token replay.

ai gateway

public + internal
  • /api/v1/ai: translate · cards · speech · title · pdf-profile
  • AI_ACCESS entitlement + hourly rate limit before any spend
  • Fingerprint cache — identical lookups skip the provider call
  • Owns the backend side of the worker job protocol
JSON prompts + server-side schema validation, one corrective retry — structured output is enforced by the application rather than left to the model alone.

translation

hexagonal
  • Books → chapters → chunks, glossary with automatic term extraction and dismissed suggestions
  • Style settings, retranslation, terminology checks, source-text lookup
  • Source-to-translation alignment spans, notes, per-chunk history, approvals
  • BOOK_TRANSLATION entitlement gates the high-token-cost routes
Real ports-and-adapters: use cases in application/port/in, web+JPA+AI at the edge.

git-archive

standalone module
  • Each translated book is a bare Git repository under /data/git
  • Snapshots, branches, merge preview, checkout, restore
  • Share links and reviewable suggestions — like pull requests for translations
  • Remote projects: inspect and import, then pull upstream changes
Contains no Reader-specific code — a generic DocSet→Git engine packaged as a standalone Maven module.

exercise / telegram

public API + bot
  • Exercise sets generated from the user's existing vocabulary-card jobs
  • Gap-fill and multiple-choice answers checked locally · free-form graded by AI
  • Bot: link-code pairing, /exercise, share — outbound long polling
  • Exercise pages rendered as plain HTML for Telegram
The bot reconstructs the vocabulary list from card-job payloads — no separate vocabulary sync needed.

app / admin

public + admin
  • Hosts the signed APK used by the direct build's updater
  • Dictionary packs, app assets (favicon, logos)
  • Admin: users, permissions, model grants, job inspection
  • Privacy policy + legal pages served statically
The Play build uses no-op updater stubs via flavors — one codebase, two distribution models.
06 — Where data lives

Data split between device and server

Reading data stays on the device; the server stores only what its services need. On the server, PostgreSQL is the authoritative store: Flyway manages the schema, and the application validates its entities against it.

PostgreSQL — server

~30 Flyway migrations · ddl-auto=validate
usersuser_permissionsrefresh_tokens ai_jobstranslate_cachemodel_grants mail_codes (sha256)altcha_spent translation_bookstranslation_chapterstranslation_chunks translation_glossary_termstranslation_chunk_notesbook_suggestions exercise_setstelegram_linkstelegram_link_codes app_assetsapp_apkdict_filedict_missdict_extra

Each translated book also has a bare Git repository on disk. The repository preserves its version history; the database rows support the active workflow.

Room + files — the device

schema v2+ · versioned migrations · exported Room schemas
booksbookmarksdecksknown_wordsreader_notes vocab_cardsreview_statesreview_logs files: dict packsfiles: audiofiles: PDF heights

Session tokens are encrypted with an Android Keystore-backed key and are not stored in the database. None of this data is required on the server — uninstalling removes the local copy.

07 — How things talk

REST and worker-initiated job processing

There is no message broker or WebSocket on the critical path. The important property is the direction of the exchange: the AI worker calls the server, not the other way around.

client → server

HTTPS · JSON
  • App & SPA call REST with a Bearer JWT
  • 401 → refresh-rotate → retry once, then logout
  • App polls GET /api/v1/jobs for AI results
  • Contract lives in docs/api/mobile-api.yaml

worker → server

pull · long-poll
  • POST /internal/ai/jobs/claim?wait=30 — the request stays open until a job becomes available
  • POST /internal/ai/jobs/{id}/events — progress & results pushed back
  • Retry attempts, recovery of abandoned claims (reaper), finishReason handling
  • X-Internal-Token, constant-time compare, fail-closed

server → services

outbound
  • Mail relayed through plexus-mail's internal route
  • Telegram bot long-polls the Bot API — no webhook to expose
  • Worker catalog read for model metadata (cached, fail-open)

Why the worker initiates requests

design note
  • The worker exposes no inbound endpoint — it can run anywhere
  • One worker type serves multiple products' cores
  • Long polling delivers jobs with near-push latency, no broker
  • The reaper makes jobs recoverable after a worker crash
08 — Follow one request

The path of a card-generation request

A user long-presses the word éphémère in a French novel. The following steps show how the request passes through the system and becomes a card.

Android · UI

Selection in the WebView page

The JS layer in the page captures the selection with sentence context and calls the Kotlin bridge.

App → Server

POST /api/v1/ai/cards

Authorization: Bearer … — the JWT carries the user's entitlements.

Server · gates

Three checks before a paid model call

AI_ACCESS authority → per-user hourly rate limit → fingerprint cache. A repeat lookup returns instantly.

Server · queue

A job record is created

Persisted in ai_jobs with a requestId that will correlate every later event.

Worker → Server

The worker pulls the job

The worker's long-poll request to /claim?wait=30 returns the job — no inbound port needed on the worker.

Worker → Provider

The only service holding provider credentials

plexus-ai calls the model. Provider credentials are never exposed to the core backend or the app.

Worker → Server

Returning events and results

/jobs/{id}/events reports completion. finishReason decides: stop is success, max_output_tokens triggers one retry with a higher limit, refusals are returned without a retry.

Server · validate

Validating the response structure

The response is schema-validated server-side; an invalid result triggers exactly one corrective retry.

App · done

Retrieving the result and scheduling review

The app's GET /api/v1/jobs picks up the result; the card is saved to Room and FSRS assigns its first review.

09 — Trust model

Who can see what

The goal isn't to encrypt everything — it's avoiding the transfer of the user’s personal library to the server in the first place.

The user’s device // no library synchronization

  • Books, reading positions, bookmarks
  • Vocabulary cards and full review history
  • Cached dictionary packs and audio
  • Session tokens (encrypted using Android Keystore)

Only required data on the server

  • Account, entitlements, rate-limit counters
  • AI job payloads — the selected word and its sentence
  • Translated books uploaded by the user
  • Mail codes as sha256(code:userId)

Deliberate limits of the server-side application

  • Call provider APIs — credentials live in the plexus-ai worker
  • Read the user’s library — it is not synchronized by default
  • Reuse a rotated refresh token — the old one is invalidated
  • Run a billable AI request without an entitlement check

Two access perimeters

  • /api/** — JWT filter, then EmailVerifiedFilter
  • /internal/** — separate chain, X-Internal-Token
  • Token compare is constant-time; unset means closed
  • Logs contain IDs and payload sizes — never text or payloads
10 — On the device

The app as a local reading system

Format-specific engines implement the same interface; a bundled JavaScript layer does the typesetting inside WebView.

Format engines

core.books.engine
  • EPUB — WebView-rendered, chapter-paginated
  • FB2/TXT — parsed to a normalized publication, block layout
  • PDF — bitmap mode, or reflowed into a scrolling HTML feed
  • DjVu — bitmap-rendered through the same session interface
  • One ReaderEngine surface: open · TOC · progress · restore

Paging layer

JS + Kotlin
  • reader-pager.js bundled from real sources, not one large string
  • Typed PagerCommand surface — no dynamically assembled eval calls
  • Double-buffered WebView slots — the next chapter renders in advance
  • Position stored as an exact scroll fraction, survives close/reopen

Offline capabilities

Room + Keystore
  • FSRS scheduler in pure, testable Kotlin
  • Dictionary packs queried locally after one download
  • Pronunciation audio cache; guest mode never needs an account
  • Real Room migrations — no destructive fallback

Two build variants, one codebase

distribution
  • direct — downloads updates from the server-hosted APK
  • play — updater calls become no-op stubs for store policy
  • Release builds fail if the base URL is not HTTPS
  • Unencrypted traffic allowed only to emulator loopback in debug builds
operational example

A scroll-restoration failure after enabling content-visibility

To reduce layout costs for very long PDF documents, each source page became a section with content-visibility: auto and a measured intrinsic height — the layout cost of a 200-page document dropped to whatever was on screen. But restoring a saved position suddenly started taking the reader back to page one and overwriting the saved position with {"index":0}.

The mechanism was subtle: skipped sections left Blink's scroll-anchoring algorithm without a stable anchor, so ~150 ms after a correct restore the engine silently reset scrollTop to zero. The app's heuristic — "moved >4px means the user scrolled" — treated that as a gesture, released the position-restoration lock and saved the zero. The fix, verified on a device: disable overflow-anchor on the feed, keep the pin until a real touch/pointer/wheel gesture, and re-assert the target while the layout settles.

before
restore target 0.6437
anchoring resets scrollTop → 0
persisted {"index":0}
after
restore target 0.6437
measured scrollTop = 296 092 px
persisted 0.6437021 — pixel-accurate
11 — The translation platform

Book translation as a versioned process

The second half of the product: a web workspace that translates entire books — and a versioning engine that treats translated text like source code.

Processing steps

Upload EPUB → chapters detected → text split into chunks
AI translates the book one chunk at a timethe glossary keeps terminology consistent · style configurable · flex-tier pricing
Human review: approve, edit, note, check terminologyalignment spans link each translated segment to its source
Commit → the book becomes a Git repository
reader-export → bilingual book in the Android app

What Git versioning enables

a4f9c21 translate ch. 07–09 (gpt-5, flex)
b17e3d0 glossary: 42 terms checked for consistency
91cc55a review: approved 31 chunks
* branch alt-ending — 3 commits ahead
* suggestion "ch. 4, para. 12: smoother wording" → accept / reject
* upstream pull updates from a shared project
  • →Branches for alternate translations
  • →Preview a merge before applying it
  • →Suggestions work like pull requests for prose
  • →Restore any snapshot; export a .git archive
  • →The Android app can import a remote repository as a book
// git-archive is a standalone Maven module — a generic engine that maps document sets to Git objects (commits, branches, merges, remotes). It knows nothing about books, users or Spring. Reader is its first client.
12 — Operations

Build and deployment

One Docker build produces the jar and the SPA. Deployment is deliberate: the image is built on the Plexus VPS and the reader service is restarted by hand — a merge is never silently live.

main merged
feature → PR → squash
→
maven:3.9 / temurin-21
git-archive install → package
frontend-maven-plugin: npm ci + vite build
→
temurin:21-jre
non-root user · /data/git
one executable JAR serving the static SPA
→
Hetzner VPS
manual docker build
compose up -d reader · healthcheck
→
reader.plexus.ing
HTTPS only · release rejects http base URL

Runtime environment

deploy
  • Spring Boot app + Postgres (pgvector image, ready for embeddings)
  • plexus-ai runs as a separate deployment configured for this backend
  • plexus-mail delivers verification and password-reset mail
  • Secrets supplied through env vars — startup fails fast if any are missing

Also served by the backend

static
  • The translator SPA (built in-image, no separate host)
  • The signed Android APK for the direct build's updater
  • privacy-policy.html, attribution, impressum
  • Swagger UI + public, schema-only OpenAPI
13 — Complete architecture

Reader architecture overview

The complete system on one diagram. Clients are shown at the top, security boundaries in the middle, and data stores and external services at the edges.

Android
Reader app
local-first · offline
FSRS · dicts · engines
Browser
Translate SPA
upload → chunks → review
Telegram
Telegram users
bot chat · exercise links
reader-server
/api/v1
auth+jwt · ai gateway · translation
exercise · telegram · dictionaries · app · admin
/internal
jobs claim/events
data
PostgreSQL
users · jobs · books
~30 migrations
inside the service
git-archive
books as repos
separate deployment
plexus-ai
pull worker → providers
separate deployment
plexus-mail
verify · reset
external
Telegram API
bot long-poll
14 — For the curious

Technical summary

Android
Kotlin 2.0, Compose, HiltRoom · Retrofit · DataStore · minSdk 26
Backend
Java 21, Spring Boot 4.1Spring Security + JWT · Flyway · RestClient
Web
Vue 3 + TypeScript + Vitebuilt inside the Docker image
Data
PostgreSQL 17 (pgvector)~30 Flyway migrations · bare git repos
AI
worker-initiated job protocoljob claim via long polling · events · reaper · retries
Versioning
git-archivestandalone Maven module · DocSet→Git
Deploy
Docker multi-stage → Hetzner VPSmanual build · compose restart · env secrets
Testing
JUnit + Testcontainers · MockWebServerRobolectric · JS contract suite · lint checks
→ Deliberately not built: cloud sync, DRM, analytics, ads. Local-first means the app must be excellent offline — that constraint shaped every component above.