DEV Community

Cameron Archer for Tinybird

Posted on

Build a Real-Time Analytics API for a Fitness App with Tinybird

In this tutorial, we'll guide you through building a real-time analytics API for a fitness application using Tinybird. As developers, creating a backend that can handle streaming data and provide instant insights into user behavior is crucial for engaging and personalized user experiences. Whether you're tracking workout trends, app usage metrics, or individual user activity summaries, the ability to analyze and act on data in real-time is a game-changer. Tinybird is a data analytics backend for software developers. You use Tinybird to build real-time analytics APIs without needing to set up or manage the underlying infrastructure. Tinybird offers a local-first development workflows, git-based deployments, resource definitions as code, and features for AI-native developers. By leveraging Tinybird's data sources and pipes, you can ingest, transform, and serve large volumes of data through APIs with minimal latency, enabling real-time analytics at scale. In this tutorial, we will cover how to structure your data, create data sources, transform your data with pipes, and finally, deploy your APIs to production. By the end, you'll have a fully functional real-time analytics API for a fitness app.

Understanding the data

Imagine your data looks like this:

{
  "event_id": "evt_cn.?|bT&",
  "user_id": "user_775",
  "event_type": "app_open",
  "timestamp": "2025-04-27 12:44:56",
  "app_version": "1.5.5",
  "device_type": "iPhone",
  "device_os": "iPadOS",
  "session_id": "sess_~g?8 _",
  "duration_seconds": 3375,
  "activity_type": "weight_training",
  "calories_burned": 775,
  "distance_km": 2927681790,
  "heart_rate": 135,
  "location_lat": 2927719.5499,
  "location_lon": 2927559.3556
}
Enter fullscreen mode Exit fullscreen mode

This data represents events generated by users interacting with a fitness app, detailing everything from the type of workout to the device used. To store this data in Tinybird, create a data source with the following .datasource file:

DESCRIPTION >
    Stores fitness app events/activities from users

SCHEMA >
    `event_id` String `json:$.event_id`,
    `user_id` String `json:$.user_id`,
    `event_type` String `json:$.event_type`,
    `timestamp` DateTime `json:$.timestamp`,
    `app_version` String `json:$.app_version`,
    `device_type` String `json:$.device_type`,
    `device_os` String `json:$.device_os`,
    `session_id` String `json:$.session_id`,
    `duration_seconds` Int32 `json:$.duration_seconds`,
    `activity_type` String `json:$.activity_type`,
    `calories_burned` Int32 `json:$.calories_burned`,
    `distance_km` Float32 `json:$.distance_km`,
    `heart_rate` Int32 `json:$.heart_rate`,
    `location_lat` Float64 `json:$.location_lat`,
    `location_lon` Float64 `json:$.location_lon`

ENGINE "MergeTree"
ENGINE_PARTITION_KEY "toYYYYMM(timestamp)"
ENGINE_SORTING_KEY "timestamp, user_id, event_type"
Enter fullscreen mode Exit fullscreen mode

This schema carefully selects column types to optimize storage and performance, using sorting keys to enhance query efficiency. For data ingestion, Tinybird's Events API allows you to stream JSON/NDJSON events from your application frontend or backend with a simple HTTP request. This real-time nature and low latency are ideal for fitness apps where timely data is crucial. Here's how you can send data:

curl -X POST "https://api.europe-west2.gcp.tinybird.co/v0/events?name=app_events&utm_source=DEV&utm_campaign=tb+create+--prompt+DEV" \
  -H "Authorization: Bearer $TB_ADMIN_TOKEN" \
  -d '{...}'
Enter fullscreen mode Exit fullscreen mode

Additionally, for event/streaming data, the Kafka connector can be beneficial for integrating with existing Kafka streams. For batch or file data, the Data Sources API and S3 connector provide flexible ingestion options. Use the Tinybird CLI for command-line interactions:

tb datasource append app_events.datasource 'app_events.ndjson'
Enter fullscreen mode Exit fullscreen mode

Transforming data and publishing APIs

With your data ingested into Tinybird, the next step is to transform it and publish APIs using pipes.

Batch Transformations and Real-time Transformations

Tinybird pipes can perform both batch transformations (copies) and real-time transformations (Materialized views). When applicable, materialized views pre-aggregate data, significantly speeding up API response times.

Creating API Endpoints

For each endpoint, you will define a pipe that executes SQL queries to transform and serve the data. Here’s how you can create APIs for popular activities, app usage metrics, and user activity summary:

Popular Activities Endpoint

DESCRIPTION >
    Get most popular activities based on user engagement

NODE popular_activities_node
SQL >
    SELECT 
        activity_type,
        count(*) as activity_count,
        count(DISTINCT user_id) as user_count,
        avg(duration_seconds) as avg_duration,
        avg(calories_burned) as avg_calories,
        avg(distance_km) as avg_distance
    FROM app_events
    WHERE event_type = 'workout_completed'
    AND timestamp >= {{DateTime(start_date)}}
    AND timestamp <= {{DateTime(end_date)}}
    GROUP BY activity_type
    ORDER BY user_count DESC
    LIMIT {{Int32(limit, 10)}}

TYPE endpoint
Enter fullscreen mode Exit fullscreen mode

This pipe creates an endpoint that aggregates workout data to find the most popular activities. It showcases the use of query parameters (start_date, end_date, limit) to make the API flexible.

App Usage Metrics Endpoint

DESCRIPTION >
    Get app usage metrics over a time range with optional filters

NODE app_usage_metrics_node
SQL >
    SELECT 
        toStartOfDay(timestamp) as day,
        count(DISTINCT user_id) as daily_active_users,
        count(DISTINCT session_id) as total_sessions,
        count(*) as total_events,
        avg(duration_seconds) as avg_session_duration,
        countIf(event_type = 'app_open') as app_opens,
        countIf(event_type = 'workout_completed') as workouts_completed
    FROM app_events
    WHERE device_os = {{String(device_os)}}
    AND app_version = {{String(app_version)}}
    AND timestamp BETWEEN {{DateTime(start_date, '2023-01-01 00:00:00')}} AND {{DateTime(end_date, '2023-12-31 23:59:59')}}
    GROUP BY day
    ORDER BY day

TYPE endpoint
Enter fullscreen mode Exit fullscreen mode

This endpoint calculates daily app usage metrics, demonstrating filtering by device OS and app version.

User Activity Summary Endpoint

DESCRIPTION >
    Get activity summary for a specific user over a time period

NODE user_activity_summary_node
SQL >
    SELECT 
        user_id,
        countIf(event_type = 'workout_completed') as total_workouts,
        sum(duration_seconds) as total_duration_seconds,
        sum(calories_burned) as total_calories_burned,
        sum(distance_km) as total_distance_km,
        avg(heart_rate) as avg_heart_rate,
        COUNT(DISTINCT activity_type) as unique_activities
    FROM app_events
    WHERE user_id = {{String(user_id, '12345')}}
    AND timestamp BETWEEN {{DateTime(start_date, '2023-01-01 00:00:00')}} AND {{DateTime(end_date, '2023-12-31 23:59:59')}}
    GROUP BY user_id

TYPE endpoint
Enter fullscreen mode Exit fullscreen mode

This API provides a comprehensive summary of a user's activities, suitable for personal dashboards or fitness tracking features.

Deploying to production

Deploying your project to production with Tinybird is as simple as running tb --cloud deploy. This command publishes your data sources and pipes to Tinybird Cloud, creating scalable, production-ready API Endpoints. Tinybird manages resources as code, integrating seamlessly into CI/CD pipelines for continuous deployment. To secure your APIs, Tinybird uses token-based authentication. Here’s how to call your deployed endpoints:

curl -X GET "https://api.tinybird.co/v0/pipes/popular_activities.json?token=%24TB_ADMIN_TOKEN&utm_source=DEV&utm_campaign=tb+create+--prompt+DEV"
Enter fullscreen mode Exit fullscreen mode

Conclusion

Throughout this tutorial, you've learned how to build real-time analytics APIs for a fitness app using Tinybird. From designing data schemas and ingesting streaming data to transforming that data and deploying scalable APIs, you now have the tools to implement similar solutions in your own projects. The technical benefits of using Tinybird include efficient data management, flexible API creation, and seamless deployment workflows. Sign up for Tinybird to build and deploy your first real-time data APIs in a few minutes.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.