Inspiration

It's 2 AM. Your mind is racing. Your body is exhausted. But sleep won't come.

We've all been there—lying awake, spiraling through worries about tomorrow's presentation, yesterday's mistake, or an endless to-do list. Traditional sleep apps offer passive solutions: counting sheep, sleep sounds, breathing exercises. But they miss the root cause: unresolved thoughts demanding attention.

The inspiration for Insomnia Butler came from a simple realization: you can't sleep when your mental RAM is full. We needed something that doesn't just distract you, but actively helps you process, categorize, and "park" your worries so your mind can finally rest. This led us to combine Cognitive Behavioral Therapy for Insomnia (CBT-I) principles with modern AI technology to create a true thought partner—not just another sleep tracker.

What it does

Insomnia Butler is an AI-powered companion that resolves the root cause of late-night wakefulness: a racing mind. Unlike traditional sleep apps, the Butler engages in structured, therapeutic dialogue to organize your thoughts, provide cognitive reframing, and guide you into a restful state.

Core Features:

🧠 AI Thought Clearing Engine - A chat interface powered by Gemini that acts as your personal cognitive coach, using Socratic questioning to guide you to resolve worries rather than just venting. The Butler can actively assist you by:

  • 🎵 Playing sleep sounds directly in the chat
  • 📅 Scheduling reminders for tomorrow so you can let go today
  • 🚫 Sending gentle notification nudges when you open distracting apps during bedtime
  • 🧘 Launching breathing exercises when it detects high anxiety

📊 Advanced Sleep Architecture Tracking - Goes beyond simple "hours slept" with high-fidelity metrics including sleep stages (Deep, Light, REM, Awake), physiological recovery (Resting Heart Rate, HRV, Respiratory Rate), efficiency scoring, and interruptions tracking.

🔗 Health Data Integration - Seamlessly syncs sleep data from Apple Health (iOS) and Health Connect (Android), supporting devices like Apple Watch, Oura, Fitbit, and Samsung Health with smart auto-sync and manual import options.

🎵 Immersive Sleep Sounds & Ambience - Curated library of high-quality audio landscapes with 3D glassmorphic album art, pro playback controls, and AI-suggested audio based on your current mood.

🧘 Interactive Breathing Coach - Integrated breathing widget featuring guided visuals for Box Breathing (4-4-4-4 technique) to help regulate your nervous system.

📅 Historical Intelligence & Analytics - Swipeable strip or full monthly calendar view, Trend Insights dashboard (Latency, Consistency, Streak), and daily mood tracking.

🚫 Smart Distraction Nudges - Intelligent notification system that detects when you open distracting apps (social media, games) during your scheduled bedtime window and sends gentle high-priority reminders to help you stay on track with your sleep goals.

Daily Butler's Insights – An automated, proactive system that works while you sleep. Utilizing persistent Future Calls, the backend autonomously wakes up before you do, analyzing your sleep stages and journal entries with Gemini AI to generate actionable "Butler's Tips" tailored to your specific wake-up time.

💬 Context-Aware Memory - Uses Vector Embeddings (pgvector) to remember your past worries and journals, providing continuity across sessions. The Butler learns your patterns and provides personalized support.

How we built it

Architecture:

We built Insomnia Butler using a modern, scalable architecture:

  • Frontend: Flutter (Dart) for cross-platform mobile development with beautiful glassmorphic UI components using flutter_animate, glass_kit, and google_fonts
  • Backend: Serverpod 3.0 (Dart) as our intelligence layer, handling AI orchestration, sleep analytics, and data management
  • AI Intelligence: Google Gemini for thought processing, cognitive reframing, and embeddings generation
  • Vector Search: pgvector (PostgreSQL) for RAG (Retrieval-Augmented Generation) to provide context-aware memory
  • Database: PostgreSQL 18.1 for robust data persistence
  • Infrastructure: Deployed on Serverpod Cloud with managed PostgreSQL, automatic scaling, and zero-downtime deployments. Dockerized container environment with load balancing for high-availability production capability.
  • Health Integration: Apple HealthKit and Android Health Connect for seamless wearable data sync

Key Technical Implementations:

  1. AI Thought Processing Pipeline: We created a sophisticated endpoint in Serverpod that orchestrates the entire thought-clearing experience. When a user shares a worry, the system:

    • Loads conversation context from previous sessions
    • Builds a CBT-I-informed system prompt
    • Calls Gemini API with safety guardrails
    • Extracts structured data (categories, readiness scores)
    • Generates and stores vector embeddings for future context retrieval
    • Logs analytics for pattern detection
  2. Vector Memory System: Using pgvector, we implemented semantic search that allows the Butler to remember what you worried about yesterday or last week, providing truly personalized support that improves over time.

  3. AI Agent Actions: We implemented a function-calling system where the AI can proactively take actions like playing sleep sounds, setting reminders, or adding apps to your distraction watch list—making it more than just a chatbot.

  4. Health Data Synchronization Integrated with native health platforms on both iOS and Android to import sleep sessions, heart rate data, and respiratory metrics, with smart deduplication and source attribution.

  5. Autonomous Insight Loops We moved beyond standard cron jobs by implementing Serverpod Future Calls to create self-sustaining, per-user analysis loops. The "Butler" schedules its own next "shift" based on the user's specific preferences (e.g., wake-up time), with jobs stored in the database to survive server restarts and deployments. By offloading heavy AI processing (Gemini analysis of 7-day datasets) to these background jobs, expensive computations happen without impacting user experience.

  6. Production Deployment on Serverpod Cloud We deployed Insomnia Butler to production using Serverpod Cloud, Serverpod's official managed hosting platform. This gave us one-command deployment with automatic build and containerization, managed PostgreSQL 18.1 with pgvector extension, auto-scaling infrastructure, zero-downtime rolling deployments, and production-grade security with automatic SSL certificates and encrypted connections.

Challenges we ran into

1. The "Amnesia" Problem": Initially, the Butler was helpful but forgetful. It couldn't recall that you were worried about the same presentation yesterday. We had to implement a sophisticated RAG pipeline using pgvector. The challenge wasn't just storing vectors—it was designing a schema that balanced distinct "memory types" (journal entries vs. chat history) and retrieving them fast enough to feel like a natural conversation.

2. The Health Data "Tower of Babel": Integrating Apple Health and Android Health Connect was a nightmare of data fragmentation. One platform returns sleep in "stages," the other in "sessions." Timestamps overlap. Permissions are denied silently. We built a robust normalization layer that acts as a universal translator, standardizing data from Oura, Garmin, and Apple Watch into a single coherent SleepSession model.

3. Safety in the Dark: Building a mental health companion for 2 AM users is high-stakes. The AI couldn't just be "smart"—it had to be safe. We spent hours stress-testing prompts to ensure the Butler detects crisis language without being an alarmist, and provides CBT-I guidance without offering medical advice. Balancing "warmth" with "safety" was our toughest prompt engineering challenge.

4. The Latency Trap: At 2 AM, waiting 3 seconds for a response feels like an eternity. Our initial chains (Context -> RAG -> Prompt -> Generation) were too slow. We optimized this by parallelizing context fetching and implementing optimistic UI updates, ensuring the Butler feels like it's listening, not loading.

5. Smart Notifications vs. OS Restrictions: Building the "Distraction Nudge" system meant fighting the OS. Android restricts background processes heavily to save battery. We had to leverage the Usage Stats API carefully and implement a robust localized notification scheduling system that works reliably without draining the user's battery or requiring a permanent background service.

Accomplishments that we're proud of

🎯 Solving a Real Problem: We didn't build another sleep tracker. We built a tool that actively clears mental clutter—addressing the root cause of insomnia, not just the symptoms.

💡 Context-Aware AI: The Butler genuinely remembers your past worries and patterns. This isn't a stateless chatbot—it's a companion that learns what helps YOU sleep.

🎨 Premium Design: Created a stunning glassmorphic UI optimized for 2 AM use—deep navy backgrounds, soft purple accents, subtle animations, and thoughtful micro-interactions.

🧠 Deep Serverpod Integration: We showcased Serverpod as a complete platform, not just a REST wrapper. Our backend handles AI orchestration, background jobs for analytics, vector search, real-time streaming, and complex data modeling.

🔧 Production-Ready Architecture: Successfully deployed to Serverpod Cloud with scalable, containerized infrastructure featuring automated database migrations, managed PostgreSQL with pgvector, auto-scaling capabilities, and zero-downtime deployment pipeline—making this a truly production-ready application, not just a hackathon demo.

🏥 Health Platform Integration: Successfully integrated with both Apple Health and Health Connect, handling the complexity of multiple data sources, permissions, and sync strategies.

🎵 AI Agent Actions: The Butler doesn't just talk—it can play music, set reminders, and send timely nudges to keep you on track, making it a true assistant.

What we learned

Technical Learnings:

  • Serverpod 3.0 Mastery: We gained deep expertise in Serverpod's authentication, ORM, background jobs, caching, and endpoint design. We learned how to structure a complex backend that's both performant and maintainable.

  • Vector Search & RAG: Implementing pgvector taught us about embedding generation, similarity search optimization, and how to build context-aware AI systems that improve over time.

  • AI Prompt Engineering: We learned that effective AI applications require more than just API calls—they need structured prompts, safety guardrails, response validation, and careful context management.

  • Flutter Advanced UI: We pushed Flutter's capabilities with custom glassmorphic components, complex animations, and platform-specific integrations.

Product Learnings:

  • Focus Wins: By focusing on one core feature (thought clearing) and doing it exceptionally well, we created something more valuable than a feature-bloated app.

  • User Psychology: We learned about CBT-I principles, sleep psychology, and how to design interventions that actually help people change behavior.

Process Learnings:

  • Thinking in "Prompt-First": We realized that for an AI app, the System Prompt IS the product. We treated our prompts like code—version controlling and unit testing them. We learned that a one-word change in a prompt could improve the user experience more than 100 lines of Dart code.

  • Incremental Deployment: Our phased approach (Core → Intelligence → Polish) ensured we always had a working app.

What's next for Insomnia Butler

Short-term:

  • Smart Home Automation: Enable the AI Butler to directly control smart home devices as an intervention tool—automatically dimming lights, adjusting thermostat temperature, and triggering sleep scenes when it detects you're ready for bed
  • Personalized Intervention Strategies: Expand beyond CBT-I to include ACT (Acceptance and Commitment Therapy) and mindfulness-based approaches
  • Social Proof: Community features showing "1,247 people fell asleep faster this week"

Medium-term:

  • Adaptive Learning: Machine learning models that predict which intervention strategies work best for each user's thought patterns
  • Voice Interface: Hands-free interaction for those who don't want to type at 2 AM
  • Sleep Coaching Programs: Structured 4-week programs for chronic insomnia

Long-term Vision:

  • Clinical Validation: Partner with sleep researchers to validate effectiveness through peer-reviewed studies
  • Global Expansion: Multi-language support and culturally-adapted CBT-I approaches
  • Platform Expansion: Web app, smartwatch app, and integrations with meditation apps

Our Mission: Make quality sleep accessible to everyone by combining cutting-edge AI with evidence-based psychology. We believe that by helping people clear their minds, we can improve not just their sleep, but their overall mental health and quality of life.

Try the App

🌐 Try it now (Web): https://naazimsnh02.serverpod.space/app
Note: Optimized for mobile devices

📱 Full Mobile Experience (Android APK): Download APK
Installation: Enable "Install from unknown sources" in settings

Built With

  • android-health-connect
  • apple-healthkit
  • audio-service
  • aws-alb
  • aws-ecs
  • aws-fargate
  • aws-rds
  • cbt-i
  • dart
  • docker
  • flutter
  • flutter-animate
  • flutter-local-notifications
  • google-fonts
  • google-gemini
  • grpc
  • installed-apps
  • just-audio
  • package-info-plus
  • path-provider
  • permission-handler
  • pgvector
  • postgresql
  • rag-(retrieval-augmented-generation)
  • rest-api
  • serverpod
  • serverpod-auth
  • shared-preferences
  • table-calendar
  • timezone
  • url-launcher
  • usage-stats
  • vector-embeddings
  • vibration
Share this project:

Updates