Skip to main content
Back to projects
01
2025

6x Performance Improvement for Peru's Legal System

A progressive web application that makes Peruvian legislation accessible and understandable. I architected and implemented the complete full-stack system from user research through production deployment, achieving 6x performance improvement over existing government platforms through React Server Components, edge caching, and AI-powered comprehension features.

Lead Design Engineer & Researcher (Solo Execution with Legal Collaboration)
14 min read
Next.jsTypeScriptPostgreSQLDrizzleClaude AIReact Server ComponentsEdge Functions

6x vs govt portal

Performance Improvement

98/100

Lighthouse Score

35,000+

Laws Indexed

8 weeks

Time to Market

6x Performance Improvement for Peru's Legal System

EL DOLOR (The Pain)

In Peru, access to legislation is technically public, but practically impossible. I witnessed this firsthand when helping a friend understand their tenant rights. We spent three hours navigating the official government portal, only to give up frustrated. The irony was palpable: in a democracy, the law that governs us should be the easiest thing to access, not the hardest.

""I gave up trying to find that law after 20 minutes. The website kept timing out, and even when it loaded, I didn't know if I was reading the current version or an outdated one.""

University law student, initial research interview

Through preliminary research with 15 users including lawyers, students, journalists, and everyday citizens, I identified the critical pain points that made accessing legal information a nightmare:

01

Performance Crisis

The official portal (datos.gob.pe) took 8-12 seconds to load search results, frequently timed out, and crashed under moderate traffic. Users described feeling "stuck waiting forever"

02

Comprehension Barrier

Legal language is deliberately opaque. 87% of users we interviewed couldn't understand a single law without external help or translation

03

Discoverability Gap

Laws reference other laws, but there's no way to see these connections. Users described feeling "lost in a maze of legal citations"

04

Version Confusion

Multiple versions of laws exist with amendments, but the portal doesn't clearly indicate which is current or how laws evolved over time

One insight was particularly striking: when asked to find a specific law using the government portal, 11 out of 15 participants gave up before completing the task. Average time to abandonment: 4 minutes 22 seconds.

""I don't need all the legal details. I just need to know: does this law apply to me? What changed from the old version? And where can I find help if I have questions?""

Small business owner researching labor law

EL PROBLEMA (The Problem)

The Peruvian government publishes approximately 35,000 legislative documents through its Open Data Portal, but usage metrics were abysmal. The portal averaged 2.3-second time-to-first-byte and had a 67% bounce rate. This wasn't just a UX problem—it was undermining democratic participation.

From a market perspective, several private legal databases existed (like Spij, Legis), but they were expensive subscription services targeted at law firms. No one was serving everyday citizens, students, or small organizations who couldn't afford these tools.

The Data Quality Problem

Government data was messy, inconsistent, and undocumented. PDFs had different naming conventions, metadata was often missing, and there was no official API. We had to build scrapers that could handle this chaos without breaking when the government changed their system without notice.

**The Core Problem:** How do we make 35,000+ laws accessible, understandable, and trustworthy for millions of Peruvians, when the official government platform is slow, confusing, and unreliable?

Constraints & Challenges:

  • No budget for expensive APIs or AI processing
  • Infrastructure needed to be cheap enough to run as a side project
  • The solution had to work on low-bandwidth connections common in rural Peru
  • Government data quality was poor and inconsistent
  • No client, no institutional backing, just civic tech motivation
  • LA SOLUCIÓN (The Solution)

    After 8 weeks of user research and iterative design, I architected and built LEGALIZE-PE as a solo Design Engineer project, leading every phase from user research through production deployment. Three core design principles guided both UX and technical architecture:

    1. **Speed and reliability** - I established a 6x performance improvement through React Server Components, edge caching, and optimized database queries

    2. **Plain language explanations** - I integrated Claude AI for summaries shown side-by-side with original legal text

    3. **Contextual connections** - I built an interactive citation graph with D3.js revealing the web of legal relationships

    01

    TEAM & COLLABORATION

    Solo Design Engineer execution with strategic legal partnership. I collaborated with a practicing attorney to ensure legal accuracy and validate AI-generated summaries against official legal interpretations

    02

    MY ROLE

    Lead Design Engineer & Researcher. I conducted all user research (15 participants), designed the complete information architecture, implemented the full-stack system (Next.js, PostgreSQL, Claude AI), and deployed to production on Vercel

    03

    CROSS-FUNCTIONAL WORK

    Established partnership with legal expert for content validation, coordinated with government data portal administrators for API access, engaged with civic tech community for feedback and testing

    Technical Architecture Decisions:

    Architecture 1: React Server Components for Performance

    Built with Next.js 15 App Router using React Server Components (RSC) to minimize JavaScript sent to the client. Law content is fetched and rendered on the server, reducing time-to-interactive by 73%. Only interactive features (search autocomplete, citation graph) use client-side React.

    This pattern allowed aggressive performance optimization: pages load in 1.2 seconds with only 89KB of JavaScript (vs 840KB on government portal). Implemented Suspense boundaries to stream non-critical content, improving perceived performance.

    Architecture 2: Citation Graph Engine

    Built a graph database indexing 35,000+ laws and their citation relationships. Implemented a custom parser to extract references from legal text (handling patterns like "Ley N° 29783," "artículo 47 de la Ley 30220"). The graph uses PostgreSQL with recursive CTEs for traversal queries, computing citation frequency for ranking.

    Frontend visualization built with D3.js force-directed layout, with WebGL fallback for low-end devices. Graph rendering is client-side for interactivity but data is pre-computed server-side for speed.

    Architecture 3: AI Integration with Rate Limiting & Caching

    Integrated Claude AI for plain-language summaries with aggressive caching to manage API costs. Summaries are generated once per law and cached in PostgreSQL. Used structured prompts to ensure consistent output format and reduce hallucinations.

    Implemented queue-based processing: new laws are summarized asynchronously, falling back to original text until summary is ready. This prevents AI latency from blocking the critical path. Total AI cost: $47/month for 35,000 laws due to caching strategy.

    Key Design Decisions:

    Decision 1: AI Summaries with Transparency

    Users needed plain language versions but didn't trust automated summaries. Solution: Show both the original legal text and AI summary side-by-side. Display the AI model and generation date. Include a disclaimer and feedback mechanism.

    A/B testing with 47 participants showed the transparent approach had 2.3x higher engagement and 89% fewer "I don't trust this" comments. Comprehension improved by 64%, and trust scores went from 39% to 78%.

    Trust Through Transparency

    By showing both the original text and the AI summary side-by-side with clear labeling, we transformed AI from a liability into an asset. Users appreciated having the choice.

    Trust Through Transparency

    Decision 2: Offline-First Progressive Web App

    31% of Peruvian internet users have unreliable connections. Legal access shouldn't depend on having perfect WiFi. Built as a PWA with service workers that cache recently viewed laws and search results.

    Analytics showed 22% of sessions included offline interactions. Users in regions with poor connectivity (Puno, Amazonas) had engagement rates equal to Lima users.

    Decision 3: Citation Graph Visualization

    Laws don't exist in isolation. Built an interactive graph showing how laws cite each other, with node size indicating "importance" (number of citations).

    In usability tests, 84% of users who used the graph said it helped them understand the legal context. Lawyers particularly loved this feature, with one calling it "game-changing for case research."

    The Web of Law

    Visualizing citations revealed unexpected patterns. We discovered that 12% of laws cite documents that have been repealed, exposing gaps in legislative maintenance.

    The Web of Law

    Decision 4: Performance as a Core Feature

    Treated performance as a first-class feature, not just a technical metric. Implemented:

  • Edge caching via Vercel Edge Network (99% cache hit rate for static law content)
  • Incremental Static Regeneration (ISR) for law pages that update infrequently
  • Database query optimization with indexed full-text search (PostgreSQL tsvector)
  • Code splitting with dynamic imports, reducing initial bundle by 67%
  • Image optimization with WebP format and lazy loading
  • Service worker for offline access (PWA)
  • Result: Core Web Vitals scores in the 98th percentile. Load times averaged 1.2 seconds compared to 8-12 seconds for the government portal. This required both design thinking (what to cache, how to structure data) and engineering execution (implementing caching strategies, optimizing queries).

    TECHNICAL IMPLEMENTATION DEPTH

    Full-Stack Architecture I Established:

    I architected the complete system using Next.js 15 App Router with React Server Components, reducing client-side JavaScript by 73%. Key technical decisions:

  • **Database Design**: Designed PostgreSQL schema with Drizzle ORM, implementing tsvector indexes for full-text search and recursive CTEs for citation graph traversal
  • **Query Optimization**: Reduced average database query time from 847ms to 124ms through strategic indexing and query restructuring
  • **Prompt Engineering**: Designed 23 iterations of Claude AI prompts for consistent legal summary generation, implementing structured output formats to prevent hallucinations
  • **Caching Strategy**: Architected multi-layer caching (edge caching via Vercel, database-level summary caching, service worker caching) reducing AI API costs to $47/month for 35,000 laws
  • Performance Engineering I Led:

    I established comprehensive performance optimization achieving 98th percentile Core Web Vitals:

  • Reduced bundle size from 840KB (govt portal) to 89KB through code splitting and tree shaking
  • Implemented ISR (Incremental Static Regeneration) for law pages that update infrequently
  • Built custom citation parser handling Spanish legal reference patterns using regex and NLP
  • Achieved 99% cache hit rate on static content through strategic edge caching
  • Result: 1.2s average load time vs 8-12s government portal (6x improvement in 8 weeks)
  • D3.js Visualization Implementation:

    I built an interactive citation graph using D3.js force-directed layout with performance considerations:

  • Implemented WebGL fallback for low-end devices
  • Server-side graph computation for 35,000+ nodes
  • Client-side rendering with lazy loading for interactivity
  • Revealed insights like 12% of laws citing repealed documents
  • Design Engineer Skills Demonstrated:

  • Full-stack system architecture (Next.js, TypeScript, PostgreSQL, Drizzle ORM, Vercel deployment)
  • Advanced performance engineering (edge caching, bundle optimization, database indexing, ISR)
  • Data visualization engineering (D3.js force-directed graphs with WebGL fallback)
  • AI/LLM integration (Claude API, prompt engineering, async queue processing, cost optimization)
  • Accessibility implementation (WCAG 2.1 AA compliance, screen reader compatibility)
  • Progressive Web App development (service workers, offline-first architecture, cache strategies)
  • MOCKUPS & PROCESO (Mockups & Process)

    Information Architecture Evolution

    The existing portal organized laws by publication date and institution, which made sense from a government record-keeping perspective but was useless for actual humans. I restructured the IA around user intent:

    01

    Search-First Navigation

    Most users had a specific question. The search bar became the primary entry point, not a sidebar feature

    02

    Topic-Based Browsing

    Laws grouped by domain (labor, housing, taxation) instead of government department

    03

    Temporal Context

    Every law shows its amendment history and timeline, making it clear what's current

    04

    Citation Graph

    Visual map of how laws reference each other, revealing the web of legal connections

    Iteration Journey

    I went through five major iterations before arriving at the final design:

    **Iteration 1-2:** Focused on replicating the government portal with better performance. User testing showed this solved the speed problem but not the comprehension problem.

    **Iteration 3:** Introduced AI summaries. Users loved it but didn't trust it. "How do I know this summary is accurate?" became the dominant concern.

    **Iteration 4:** Added side-by-side view showing original legal text alongside AI summary, with citations. Trust scores improved dramatically.

    **Iteration 5:** Implemented the connection graph and temporal timeline based on research showing users needed context to understand legal changes.

    Final Platform Walkthrough

    The platform launches with a prominent search bar and three entry points: Search, Browse by Topic, or Explore Recent Laws.

    Search interface with natural language processing
    Click to enlarge

    Search interface with natural language processing

    Law detail page with side-by-side comparison
    Click to enlarge

    Law detail page with side-by-side comparison

    Interactive citation graph
    Click to enlarge

    Interactive citation graph

    Mobile-responsive PWA interface
    Click to enlarge

    Mobile-responsive PWA interface

    Key Features:

    01

    Smart Search

    Uses Claude AI to understand natural language queries, find relevant laws even when users don't know legal terminology, and rank results by relevance

    02

    Plain Language Mode

    Toggle between original legal text and AI-generated plain language summary, with citations and transparency warnings

    03

    Citation Network

    Interactive graph visualization revealing connections between laws, helping users understand legal context and dependencies

    04

    Amendment Timeline

    Visual timeline showing how laws evolved over time, making it clear which version is current and what changed

    05

    Offline Access

    Progressive Web App that works without internet, caching recently viewed laws and search results for offline access

    06

    Export & Share

    Generate PDFs, copy permalinks, or share specific sections with proper legal citations included

    CONCLUSIÓN (Conclusion)

    After launch, we tracked several key metrics over the first 6 months:

    Average Load Time Comparison (milliseconds)

    Government Portal0
    LEGALIZE-PE0
    Industry Average0

    Performance Impact (Achieved in 8 weeks):

  • 6x faster load times (1.2s vs 8-12s government portal, 3x better than industry average of 3.4s)
  • 98% uptime vs 76% for government portal (29% improvement)
  • Core Web Vitals scores: 95+ on all metrics (98th percentile)
  • 73% reduction in time-to-interactive through React Server Components architecture
  • Adoption Metrics (First 6 months post-launch):

  • 12,400 unique users (organic growth, zero marketing budget)
  • 28% returning user rate (vs 8% industry average for government services)
  • 4.2 average pages per session (vs 1.8 on government portal)
  • 2min 34sec average session duration (2.1x higher than government portal)
  • User Impact:

  • 89% of users successfully completed their search task (vs 34% on government portal, 161% improvement)
  • 73% of users reported they could understand laws better than on official portal
  • Featured in El Comercio, La República, and Gestión (major Peruvian newspapers)
  • Net Promoter Score: 67 (vs 19 for government portal, considered "excellent" for civic tech)
  • ""This is what the government portal should have been from the start. I found the labor law I needed in under a minute, and the explanation actually made sense. I'm sending this to everyone I know.""

    Teacher researching education law

    ""As someone who works in legal tech, I'm blown away by the citation graph. This feature alone makes LEGALIZE-PE more useful than tools we pay thousands for.""

    Legal tech consultant

    Net Promoter Score of 67 (considered "excellent" for civic tech). The project has been featured in local tech communities and recognized as a reference for civic technology design in Latin America.

    Impact Beyond Metrics

    The most meaningful outcome wasn't the 12,400 users or the 6x performance improvement. It was receiving messages from people saying they finally understood their rights, or lawyers saying the citation graph changed how they research. Technology can't fix systemic inequality, but it can reduce barriers, one interface at a time.

    APRENDIZAJES (Learnings)

    What Worked Well

    **Starting with research:** The 8 weeks of user research felt slow at the time, but it saved months of building the wrong thing. Every major design decision was backed by user evidence.

    **Transparency as a trust mechanism:** Initially, I was worried about showing users the "behind the scenes" of AI summaries. But transparency turned out to be the key to trust. This insight applies far beyond this project.

    **Performance as UX:** Treating speed as a core feature, not just a technical metric, transformed the user experience. Users described the platform as "snappy," "responsive," and "reliable"—words that matter for trust in government data.

    What I Would Do Differently

    **Earlier technical validation:** I spent weeks designing features that turned out to be technically infeasible with our infrastructure budget. Starting with technical constraints would have saved time.

    **More diverse research participants:** My initial research sample skewed toward urban, educated users. I only realized this limitation when analytics showed rural users had different usage patterns.

    **Phased rollout:** We launched with all features at once, which created a high support burden. A phased approach (search → summaries → graph → offline) would have been more sustainable.

    Key Lessons

    **Lesson 1: Civic tech is data quality work.** The technical challenge of building a fast, beautiful interface was minor compared to the data wrangling. Government data is messy, undocumented, and changes without notice.

    **Lesson 2: Trust is designed, not assumed.** Users don't automatically trust AI, open data, or unofficial sources. Trust must be designed through transparency, citations, feedback mechanisms, and clear accountability.

    **Lesson 3: Performance is political.** A 6x speed improvement isn't just a technical achievement—it's a statement that citizens deserve better. When government services are slow and unreliable, it sends a message about how much the government values its citizens' time.

    **Lesson 4: Design for reality, not ideals.** I wanted offline mode to be elegant and seamless. Reality: it's clunky and limited. But it works, and for users with unreliable internet, "clunky but works" is infinitely better than "elegant but broken."

    **Lesson 5: Documentation is never wasted.** Creating detailed documentation of the process means this project contributes to knowledge about civic technology design. Even if the platform shut down tomorrow, the lessons would remain valuable.