Getting Started with CarePet: A sample IoT App


In this guided exercise, you’ll create an IoT app from scratch and configure it to use ScyllaDB as the backend datastore.

We’ll use as an example, an application called CarePet, which collects and analyzes data from sensors attached to a pet’s collar and monitors the pet’s health and activity.

The example can be used, with minimal changes, for any IoT like application.

We’ll go over the different stages of the development, from gathering requirements, creating the data model, cluster sizing and hardware needed to match the requirements, and finally building and running the application.

Use Case Requirements

Each pet collar includes sensors that report four different measurements: Temperature, Pulse, Location, and Respiration.

The collar reads the sensor’s data once a second and sends measurements directly to the app.

Performance Requirements

The application has two parts:

  • Sensors: writes to the database, throughput sensitive

  • Backend dashboard: reads from the database, latency-sensitive

For this example, we assume 99% writes (sensors) and 1% reads (backend dashboard)

Required SLA:

  • Writes throughput of 100K Operations per second

  • Reads: latency of up to 10 milliseconds for the 99th percentile.

The application requires high availability and fault tolerance. Even if a ScyllaDB node goes down or becomes unavailable, the cluster is expected to remain available and continue to provide service. You can learn more about Scylla high availability in this lesson.

Design and Data Model

In this part we’ll think about our queries, make the primary key and clustering key selection, and create the database schema. See more in the data model design document.

Deploying the App


The example application uses Docker to run a three-node ScyllaDB cluster. It allows tracking of pet’s health indicators and consists of three parts:

  • migrate (/cmd/migrate) - creates the CarePet keyspace and tables

  • collar (/cmd/sensor) - generates a pet health data and pushes it into the storage

  • web app (/cmd/server) - REST API service for tracking the pets’ health state

Download the example code from git and change to the directory of your language of choice:

$ git clone
$ cd go

Start by creating a local ScyllaDB cluster consisting of 3 nodes:

$ docker-compose up -d

Docker-compose will spin up a ScyllaDB cluster consisting of 3 nodes (carepet-scylla1, carepet-scylla2 and carepet-scylla3) along with the app (for example go-app) container.  Wait for about two minutes and check the status of the cluster: To check the status of the cluster:

$ docker exec -it carepet-scylla1 nodetool status

Once all the nodes are in UN - Up Normal status, initialize the database. This will create the keyspaces and tables:

$ NODE1=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' carepet-scylla1)
$ docker exec -it go-app ./migrate --hosts $NODE1

expected output:

2020/08/06 16:43:01 Bootstrap database...
2020/08/06 16:43:13 Keyspace metadata = {Name:carepet DurableWrites:true StrategyClass:org.apache.cassandra.locator.NetworkTopologyStrategy StrategyOptions:map[datacenter1:3] Tables:map[gocqlx_migrate:0xc00016ca80 measurement:0xc00016cbb0 owner:0xc00016cce0 pet:0xc00016ce10 sensor:0xc00016cf40 sensor_avg:0xc00016d070] Functions:map[] Aggregates:map[] Types:map[] Indexes:map[] Views:map[]}

You can check the database structure with:

   $ docker exec -it carepet-scylla1 cqlsh
   carepet  system_schema  system_auth  system  system_distributed  system_traces

   cqlsh> USE carepet;
   cqlsh:carepet> DESCRIBE TABLES
   pet  sensor_avg  gocqlx_migrate  measurement  owner  sensor

   cqlsh:carepet> DESCRIBE TABLE pet

       owner_id uuid,
       pet_id uuid,
       address text,
       age int,
       breed text,
       chip_id text,
       color text,
       gender text,
       name text,
       species text,
       weight float,
       PRIMARY KEY (owner_id, pet_id)  
       AND bloom_filter_fp_chance = 0.01
       AND caching = {'keys': 'ALL', 'rows_per_partition': 'ALL'}
       AND comment = ''
       AND compaction = {'class': 'SizeTieredCompactionStrategy'}
       AND compression = {'sstable_compression': ''}
       AND crc_check_chance = 1.0
       AND dclocal_read_repair_chance = 0.1
       AND default_time_to_live = 0
       AND gc_grace_seconds = 864000
       AND max_index_interval = 2048
       AND memtable_flush_period_in_ms = 0
       AND min_index_interval = 128
       AND read_repair_chance = 0.0
       AND speculative_retry = '99.0PERCENTILE';

   cqlsh:carepet> exit

Next, start the pet collar simulation. Execute the following command to generate the pet’s health data and save it to the database:

$ docker exec -it go-app ./sensor --hosts $NODE1

expected output:

2020/08/06 16:44:33 Welcome to the Pet collar simulator
2020/08/06 16:44:33 New owner # 9b20764b-f947-45bb-a020-bf6d02cc2224
2020/08/06 16:44:33 New pet # f3a836c7-ec64-44c3-b66f-0abe9ad2befd
2020/08/06 16:44:33 sensor # 48212af8-afff-43ea-9240-c0e5458d82c1 type L new measure 51.360596 ts 2020-08-06T16:44:33+02:00
2020/08/06 16:44:33 sensor # 2ff06ffb-ecad-4c55-be78-0a3d413231d9 type R new measure 36 ts 2020-08-06T16:44:33+02:00
2020/08/06 16:44:33 sensor # 821588e0-840d-48c6-b9c9-7d1045e0f38c type L new measure 26.380281 ts 2020-08-06T16:44:33+02:00

Write down the pet Owner ID (the ID is the part after the # sign without trailing spaces). We will use it later. Now, start the REST API service in a separate terminal. This server exposes a REST API that allows for tracking the pet’s health state:

$ NODE1=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' carepet-scylla1)
$ docker exec -it go-app ./server --port 8000 --hosts $NODE1

expected output:

2020/08/06 16:45:58 Serving care pet at

Using the Application

Open a different terminal to send an HTTP request from the CLI:

$ docker exec -it go-app sh
$ curl -v

expected output:

> GET / HTTP/1.1
> Host:
> User-Agent: curl/7.71.1
> Accept: */*
* Mark bundle as not supporting multiuse
< HTTP/1.1 404 Not Found
< Content-Type: application/json
< Date: Thu, 06 Aug 2020 14:47:41 GMT
< Content-Length: 45
< Connection: close
* Closing connection 0
{"code":404,"message":"path / was not found"}

If you see this JSON in the end with 404, it means everything works as expected. To read an owner’s data use the previously saved owner_id as follows:

$ curl -v{owner_id}

for example:

$ curl

expected result:


To list the owner’s pets run:

$ curl -v{owner_id}/pets

for example:

$ curl

expected output:


To list each specifc pet’s sensor:

$ curl -v curl -v{pet_id}/sensors

for example: i $ curl


To review the data from a specific sensor:

$ curl{sensor_id}/values?from=2006-01-02T15:04:05Z07:00&to=2006-01-02T15:04:05Z07:00

for example:

$  curl\?from\="2020-08-06T00:00:00Z"\&to\="2020-08-06T23:59:59Z"

expected output:


To read the pet’s daily average per sensor use:

$ curl{sensor_id}/values/day/{date}

for example:

$ curl -v

expected output:


Code Structure and Implementation

The code package structure is as follows:

Name Purpose
/api swagger api spec
/cmd applications executables
/cmd/migrate install database schema
/cmd/sensor Simulates the pet's collar
/cmd/server web application backend
/config database configuration
/db database handlers (gocql/x)
/db/cql database schema
/handler swagger REST API handlers
/model application models and ORM metadata

After data is collected from the pets via the sensors on their collars, it is delivered to the central database for analysis and for health status checking.

The collar code sits in the /cmd/sensor and uses scylladb/gocqlx Go driver to connect to the database directly and publish its data. The collar sends a sensor measurement update once a second.

Overall all applications in this repository use scylladb/gocqlx for:

  • Relational Object Mapping (ORM)

  • Building Queries

  • Migrating database schemas

The web application’s REST API server resides in /cmd/server and uses go-swagger that supports OpenAPI 2.0 to expose its API. API handlers reside in /handler. Most of the queries are reads.

The application is capable of caching sensor measurements data on an hourly basis. It uses Lazy Evaluation to manage sensor_avg. It can be viewed as an application-level lazy-evaluated materialized view.

The algorithm is simple and resides in /handler/avg.go:

  • read sensor_avg

  • if there is no data, read measurement data, aggregate in memory, save

  • serve request

Additional Resources

Future Work

  • Add Sizing

  • Add Benchmarking

  • Add Java implementation

  • Add Python implementation

  • In a real-world application, it would be better to aggregate data in an internal buffer and send it once a day to the application gateway in a batch, implying techniques such as delta encoding. It could also aggregate data at a lower resolution and take measurements less frequently. The collar could notify the pet’s owner about suspicious health parameters directly or via the application.

  • Add location tracking info to send alerts when the pet enters/leaves safe zones using known WiFi networks.

  • Use the measurements to present to the pet owner health alerts, vital signs, sleeping levels, activity levels, and calories burned.