Skip to content

Troubleshooting & FAQ

This section covers frequently asked questions, common issues, and troubleshooting guides for FastSvelte development and deployment.

Frequently Asked Questions

General Questions

Q: What is FastSvelte? A: FastSvelte is a production-ready fullstack SaaS starter kit built with FastAPI (Python) and SvelteKit (TypeScript). It includes authentication, user management, payments, admin tools, and deployment configurations.

Q: Is FastSvelte suitable for both B2B and B2C applications? A: Yes! FastSvelte supports both models through the FS_MODE environment variable. B2B mode supports team-based organizations with invitations, while B2C mode creates personal organizations for each user.

Q: Can I use FastSvelte for non-SaaS applications? A: Absolutely. While optimized for SaaS, FastSvelte works well for any web application needing user management, authentication, and a modern tech stack.

Architecture Questions

Q: Why do we use suffixes like _model, _repo, _service, and _route in file names?

Here's a comparison of file structures with and without suffixes:

With suffixes (FastSvelte approach):

backend/app/
├── api/route/user_route.py
├── service/user_service.py  
├── model/user_model.py
└── data/repo/user_repo.py

Without suffixes:

backend/app/
├── api/route/user.py
├── service/user.py
├── model/user.py  
└── data/repo/user.py

Why suffixes win: - IDE clarity - When you have multiple user.py tabs open, you can't tell which is which - Search efficiency - Easier to find "user_service" than filtering through multiple "user" files - Code navigation - Jump-to-file works better with descriptive names - Team collaboration - No confusion about which file handles what

Q: Why are repositories registered as providers.Factory instead of Singleton?

We use Factory when components might maintain state or need fresh instances. Singleton is used for stateless components:

# Singleton for stateless services
user_service = providers.Singleton(UserService, user_repo=user_repo)

# Factory for repositories that might have transaction state  
user_repo = providers.Factory(UserRepo, db_config=db_config)

Q: Why do we have both service-level and route-level error handling?

Service layer throws domain-specific exceptions:

# Service
if user_exists:
    raise UserAlreadyExistsException(f"User {email} already exists")

Route layer converts to HTTP responses:

# Route  
try:
    user = await user_service.create_user(email, password)
except UserAlreadyExistsException as e:
    raise HTTPException(status_code=409, detail=str(e))

This separates business logic from HTTP concerns and makes services testable independently.

Development Questions

Q: How do I add a new API endpoint? A: Follow these steps: 1. Add route in app/api/route/ 2. Add service method in app/service/ 3. Add repository method if needed in app/data/repo/ 4. Update models in app/model/ 5. Run cd frontend && npm run generate to update API client

Q: How do I add a new database table? A: Use Sqitch migrations: 1. cd db && sqitch add table_name -n "Description"
2. Edit deploy/table_name.sql with CREATE TABLE 3. Edit revert/table_name.sql with DROP TABLE 4. Run ./sqitch.sh dev deploy

Q: How do I customize the admin dashboard? A: Admin components are in frontend/src/routes/(protected)/admin/. You can: - Modify existing admin pages - Add new admin routes - Update the admin layout in (protected)/admin/+layout.svelte - Add new dashboard widgets

Authentication Questions

Q: Why session-based auth instead of JWT? A: Session-based auth provides better security: - HTTP-only cookies prevent XSS attacks - Server-side session control - instant revocation - Simpler client code - no token management - Built-in CSRF protection with SameSite cookies

Q: How do I add social login providers? A: FastSvelte includes Google OAuth. To add others: 1. Add provider credentials to settings 2. Implement provider-specific OAuth flow in app/util/oauth_util.py 3. Add OAuth routes in app/api/route/auth_route.py 4. Update frontend login page

Q: How do I customize user roles? A: Roles are defined in the database. To add new roles: 1. Insert new role in fastsvelte.role table 2. Update role checks in services and routes 3. Add UI permissions in frontend components

Common Issues & Solutions

Setup Issues

Issue: pip install fails with dependency conflicts

ERROR: Cannot install fastapi>=0.104.0 and pydantic<2.0.0
Solution: Update your Python version to 3.12+ and use clean virtual environment:
python3.12 -m venv .venv
source .venv/bin/activate  
pip install --upgrade pip
pip install -r requirements.txt

Issue: PostgreSQL connection refused

asyncpg.exceptions.ConnectionRefusedError: Connection refused
Solution: Ensure PostgreSQL is running:
# Using Docker
docker compose up db -d

# Check if running
docker ps | grep postgres

# Verify connection
psql postgres://postgres:postgres@localhost/fastsvelte -c "SELECT 1;"

Issue: Database does not exist

asyncpg.exceptions.InvalidCatalogNameError: database "fastsvelte" does not exist
Solution: Create the database:
# Connect to PostgreSQL and create database
psql postgres://postgres:postgres@localhost -c "CREATE DATABASE fastsvelte;"

# Or use Docker
docker exec -it fastsvelte-db psql -U postgres -c "CREATE DATABASE fastsvelte;"

Development Issues

Issue: API client generation fails

Error: Could not fetch OpenAPI spec from http://localhost:8000/openapi.json
Solution: Ensure backend is running before generating client:
# Start backend first
cd backend && uvicorn app.main:app --reload

# Then generate in another terminal
cd frontend && npm run generate

Issue: Import errors with absolute imports

ModuleNotFoundError: No module named 'app.service'
Solution: Always use absolute imports from app package:
# ✅ Correct
from app.service.user_service import UserService

# ❌ Incorrect  
from ..service.user_service import UserService

Issue: Dependency injection not working

TypeError: 'NoneType' object is not callable
Solution: Ensure your module is added to wiring configuration:
# app/config/container.py
wiring_config = containers.WiringConfiguration(
    modules=[
        "app.api.route.your_new_route",  # Add this line
        # ... existing modules
    ]
)

Database Issues

Issue: Migration fails with "relation already exists"

psycopg2.errors.DuplicateTable: relation "user" already exists
Solution: Use IF NOT EXISTS in migrations:
CREATE TABLE IF NOT EXISTS fastsvelte."user" (...);

Issue: Sqitch deploy fails with permission denied

bash: ./sqitch.sh: Permission denied
Solution: Make script executable:
chmod +x db/sqitch.sh

Issue: Connection pool exhausted

asyncpg.exceptions.TooManyConnectionsError: too many connections
Solution: Adjust connection pool settings:
# app/data/db_config.py
self.pool = await asyncpg.create_pool(
    self.dsn,
    min_size=5,    # Reduce if needed
    max_size=10,   # Reduce if needed  
    command_timeout=60
)

Frontend Issues

Issue: CORS errors in development

Access to fetch blocked by CORS policy
Solution: Check CORS configuration in backend:
# app/config/settings.py
@property  
def cors_origins(self) -> list[str]:
    return {
        "dev": ["http://localhost:5173", "http://localhost:4173"],
        # ... other environments
    }.get(self.environment, [])

Issue: Authentication not persisting

User logged out after page refresh
Solution: Ensure cookies are configured properly:
// src/lib/api/axios.js
export const axiosInstance = Axios.create({
    baseURL: PUBLIC_API_BASE_URL,
    withCredentials: true  // This is crucial
});

Issue: Svelte components not updating

Component state not reactive
Solution: Use Svelte 5 runes correctly:
// ✅ Correct
let count = $state(0);

// ❌ Incorrect  
let count = 0;

Production Issues

Issue: Static assets not loading

404 Not Found for /assets/app.js
Solution: Check build configuration and base path:
// frontend/vite.config.js
export default {
    build: {
        outDir: 'build',
        assetsDir: 'assets'
    }
};

Issue: Database connection timeouts in production

asyncpg.exceptions.ServerTimeoutError: timeout
Solution: Increase connection timeout and pool settings:
# Environment variables
FS_DB_URL="postgres://user:pass@host/db?connect_timeout=60"

Issue: High memory usage

Container killed: Out of memory
Solution: Optimize container resources and add memory limits:
# Dockerfile
FROM python:3.12-slim  # Use slim image

# Add memory-efficient settings
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1

Environment-Specific Troubleshooting

Development Environment

Issue: Hot reload not working

Changes not reflected in browser
Solution: Check file watchers and ports:
# Backend
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# Frontend  
npm run dev -- --host 0.0.0.0 --port 5173

Issue: Docker volumes not mounting

Database data lost after container restart
Solution: Create external volume:
docker volume create fastsvelte-data
docker compose up db -d

Production Environment

Issue: SSL certificate errors

SSL_CERT_VERIFY_FAILED
Solution: Ensure proper SSL configuration:
# Check certificate
openssl s_client -connect yourdomain.com:443

# Verify DNS
nslookup yourdomain.com

Issue: Rate limiting too aggressive

429 Too Many Requests
Solution: Adjust rate limiting configuration:
# app/api/middleware/rate_limiter.py
def get_rate_limit(request: Request) -> str:
    if is_production():
        return "100/minute"  # Increase for production
    return "10/minute"

Performance Troubleshooting

Slow Database Queries

Issue: Queries taking too long

Query execution time > 1000ms
Solution: Add indexes and optimize queries:
-- Find slow queries
SELECT query, mean_exec_time, calls 
FROM pg_stat_statements 
WHERE mean_exec_time > 100
ORDER BY mean_exec_time DESC;

-- Add missing indexes
CREATE INDEX CONCURRENTLY idx_user_organization_active 
ON fastsvelte."user"(organization_id) WHERE is_active = true;

High Memory Usage

Issue: Memory usage constantly increasing

Memory usage: 85%+
Solution: Check for memory leaks:
# Add connection cleanup
async def cleanup_connections():
    await db_config.pool.close()

# Monitor connection pools
async def get_pool_status():
    return {
        "size": db_config.pool.get_size(),
        "active": db_config.pool.get_active_count(),
        "idle": db_config.pool.get_idle_count()
    }

Security Issues

Authentication Bypass

Issue: Users accessing protected routes without login

Unauthorized access to /admin
Solution: Verify route protection:
@router.get("/admin/users")
async def list_users(
    current_user: CurrentUser = Depends(min_role_required(Role.SYSTEM_ADMIN))
):
    # Ensure dependency is applied

Session Hijacking

Issue: Sessions being stolen or reused Solution: Implement proper session security:

# Rotate session tokens on login
async def login(email: str, password: str):
    # ... authenticate user

    # Generate new session token
    new_token = secrets.token_urlsafe(32)

    # Invalidate old sessions for this user
    await session_repo.delete_by_user_id(user.id)

    # Create new session
    await session_repo.create(user.id, hash_token(new_token))

Monitoring & Debugging

Application Logs

View backend logs:

# Docker logs
docker logs fastsvelte-api --follow

# Local development
tail -f backend/app.log

View frontend logs: - Open browser DevTools → Console - Check Network tab for API errors - Monitor Application tab for localStorage/cookies

Database Monitoring

Check active connections:

SELECT count(*) as active_connections 
FROM pg_stat_activity 
WHERE state = 'active';

Monitor query performance:

SELECT 
    query,
    mean_exec_time,
    calls,
    total_exec_time
FROM pg_stat_statements 
ORDER BY mean_exec_time DESC
LIMIT 10;

Health Checks

API health check:

curl https://yourdomain.com/health

Database connectivity:

curl https://yourdomain.com/health/db

External services:

curl https://yourdomain.com/health/services

Getting Help

Self-Help Resources

  1. Check logs - Always start with application and error logs
  2. Review configuration - Verify environment variables and settings
  3. Test connections - Verify database, API, and external service connectivity
  4. Consult documentation - Review relevant sections in this documentation

Community Support

  1. GitHub Issues - Report bugs and feature requests
  2. Documentation - Check all sections of this documentation
  3. API Documentation - Use interactive docs at /docs endpoint
  4. Code Examples - Review example implementations in the codebase

When Reporting Issues

Include the following information:

  1. Environment details - Development/production, OS, versions
  2. Error messages - Complete error traces and logs
  3. Configuration - Relevant environment variables (sanitized)
  4. Steps to reproduce - Minimal reproduction steps
  5. Expected behavior - What should happen vs what actually happens

Quick Diagnostics Script

#!/bin/bash
# FastSvelte Health Check

echo "=== FastSvelte Diagnostics ==="

# Check Python version
echo "Python version: $(python --version)"

# Check Node version  
echo "Node version: $(node --version)"

# Check database connection
if psql $FS_DB_URL -c "SELECT 1;" &>/dev/null; then
    echo "✅ Database connection: OK"
else
    echo "❌ Database connection: FAILED"
fi

# Check backend API
if curl -s http://localhost:8000/health &>/dev/null; then
    echo "✅ Backend API: OK"
else
    echo "❌ Backend API: FAILED"
fi

# Check frontend
if curl -s http://localhost:5173 &>/dev/null; then
    echo "✅ Frontend: OK" 
else
    echo "❌ Frontend: FAILED"
fi

echo "=== End Diagnostics ==="

This comprehensive troubleshooting guide should help resolve most common FastSvelte issues. For additional help, consult the other documentation sections or create an issue in the repository.