Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 30 ยท Cassandra Data Model

Data types, collections and UDTs

Learn the Cassandra types you will use daily: uuid and timeuuid, timestamp, decimal, list, set, map, frozen values, user-defined types and counters.

A Cassandra table is only as good as its column types. Choosing text or uuid is easy. The interesting decisions are the ones that behave differently from SQL: a timeuuid that sorts by time, collections that live inside one cell, frozen values that are rewritten as a whole, and counter columns that can only be incremented. Each of them changes what happens when a write is retried, and in a distributed system writes are retried all the time.

This lesson tours the types, shows the CQL in read-only blocks, and then uses JavaScript stand-ins to make the rules visible. The stand-ins imitate the semantics; they are not Cassandra and they say nothing about its speed or storage format. If you have not met tables and primary keys yet, read CQL: keyspaces, tables and basic queries and Partition keys and clustering keys first.

The everyday scalar types

Most columns use a small set of types:

CQL type Holds Notes
text (alias varchar) UTF-8 string The default choice for names, titles, JSON strings
int, bigint, smallint, varint Whole numbers varint is arbitrary size; int is 32 bits
float, double Binary floating point Rounding errors, so never for money
decimal Exact decimal numbers Use for prices and amounts
boolean true or false
timestamp A moment in time Stored with millisecond precision
date, time A calendar day, a time of day Useful for bucketing
uuid 128-bit identifier Random (version 4) ids are common
timeuuid A version 1 UUID Contains a timestamp, so it sorts by time
blob, inet Raw bytes, an IP address
SQL
CREATE TABLE shop.products (
  product_id  uuid PRIMARY KEY,
  name        text,
  price       decimal,
  in_stock    boolean,
  created_at  timestamp
);

INSERT INTO shop.products (product_id, name, price, in_stock, created_at)
VALUES (uuid(), 'Desk lamp', 24.90, true, toTimestamp(now()));

uuid() produces a random id and now() produces a timeuuid. Because a UUID is generated by the client or the coordinator, nobody has to coordinate an auto-increment counter across a cluster. That is the reason Cassandra tables use UUIDs where a relational table would use SERIAL.

Why timeuuid exists

A timeuuid embeds the time at which it was created, plus enough extra bits to make collisions practically impossible, even when two machines generate one in the same millisecond. Cassandra sorts timeuuids by their embedded time, which makes them ideal clustering keys for "newest first" lists:

SQL
CREATE TABLE chat.messages (
  room_id  uuid,
  sent_id  timeuuid,
  author   text,
  body     text,
  PRIMARY KEY ((room_id), sent_id)
) WITH CLUSTERING ORDER BY (sent_id DESC);

SELECT * FROM chat.messages WHERE room_id = ? AND sent_id > minTimeuuid('2026-01-01 00:00:00+0000');

A plain timestamp as clustering key would silently overwrite a row when two messages share the same millisecond, because the primary key would be identical. A timeuuid keeps both. You can pull the time back out with toTimestamp(sent_id).

Collections: list, set and map

Collections store several values in one column.

SQL
CREATE TABLE shop.users (
  user_id  uuid PRIMARY KEY,
  name     text,
  emails   set<text>,
  phones   map<text, text>,
  recent   list<text>
);

UPDATE shop.users SET emails = emails + {'[email protected]'} WHERE user_id = ?;
UPDATE shop.users SET phones['mobile'] = '555-0100'          WHERE user_id = ?;
UPDATE shop.users SET recent = recent + ['lamp']             WHERE user_id = ?;
  • A set has no duplicates and is kept sorted by element.
  • A map holds key-value pairs, sorted by key. Updating phones['mobile'] touches just that entry.
  • A list keeps insertion order and allows duplicates.

Cassandra stores each element of a non-frozen collection as its own cell. That is why emails + {...} can be done without reading the old value first: the write only adds a cell. Appending to a list is also a plain write, but it is not idempotent: sending the same append twice puts the element in twice. Setting a list element by index (recent[0] = 'x') or removing by position requires reading the list first, which is slower and is best avoided.

Collections are meant to be small. Cassandra reads a collection as a whole, and very large ones slow down reads and cause trouble. If you expect hundreds of entries that keep growing, model them as rows with a clustering key instead.

Stand-in 1: collection semantics

The program below mimics the three collections and replays each write twice, the way a client retries after a timeout. Look at which collections end up with duplicates.

JS Retrying writes on a list, a set and a map

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The set and the map absorbed the retry, because adding an existing element or setting an existing key changes nothing. The list now contains "lamp" twice. Real Cassandra behaves the same way for list appends, so prefer sets and maps for data that you might write more than once.

Frozen values and user-defined types

A user-defined type (UDT) groups named fields into one value:

SQL
CREATE TYPE shop.address (
  street  text,
  city    text,
  zip     text
);

CREATE TABLE shop.customers (
  customer_id  uuid PRIMARY KEY,
  home         frozen<address>,
  past_homes   list<frozen<address>>
);

frozen tells Cassandra to serialize the whole value into a single cell. A frozen value is written and read as one blob: you cannot update just the city of a frozen address, you replace the entire address. In exchange, frozen values are compact, and only frozen collections and UDTs can appear inside a primary key or be nested inside another collection. Newer Cassandra versions also allow non-frozen UDTs, where each field is its own cell with its own timestamp and individual fields can be updated. Collections nested inside collections still need frozen.

The difference matters when two clients update different fields at nearly the same time. Cassandra resolves conflicts per cell with a "last write wins" rule that compares write timestamps (the full story is in Replication and tunable consistency).

flowchart LR
    subgraph NF["Non-frozen UDT: one cell per field"]
        A1["street (t=1)"]
        A2["city (t=5)"]
        A3["zip (t=1)"]
    end
    subgraph FZ["Frozen UDT: one cell for everything"]
        B1["street + city + zip (t=6)"]
    end

A non-frozen value keeps a timestamp per field; a frozen value has one timestamp for the whole thing.

Stand-in 2: frozen versus per-field cells

Two clients start from the same address. Client A changes only the city at time 5. Client B changes only the street at time 6, but because B read the old address first, a frozen write has to send the old city along.

JS Two writers, two storage styles

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With per-field cells both edits survive. With the frozen value, B's whole-value write wins and A's new city is lost. Neither design is wrong: frozen values are simpler and can be used as keys; per-field cells suit data that different writers update independently.

Counters

A counter column holds a 64-bit number that you can only change by adding or subtracting:

SQL
CREATE TABLE shop.page_stats (
  page_id  text PRIMARY KEY,
  views    counter
);

UPDATE shop.page_stats SET views = views + 1 WHERE page_id = 'home';

Counters live in tables where every non-key column is a counter. You cannot INSERT them, give them a TTL, or set them to a value. The big caveat is that an increment is not idempotent. If the client times out, it does not know whether the increment happened, and a retry may count the same page view twice. Counters are good for approximate statistics such as view counts. They are a poor choice for money or stock levels, where you should store each event as its own row and add them up (see Time-series and bucketing patterns).

JS A lost reply and a double count

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Three page views happened. The counter reports four; the event rows, which are keyed by a unique id, report three. This is the same trade-off you saw with lists: operations that "add to what is there" cannot tell a retry from a new request, while writes that "set this exact key" can.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a timeuuid often better than a timestamp as a clustering column for chat messages?

    Two rows with identical primary keys overwrite each other. A timeuuid adds extra bits to the embedded time, so concurrent messages stay distinct and still sort by time.
  2. 2. A client retries an append to a list<text> column after a timeout. What can happen?

    List appends are plain writes without a uniqueness check, so they are not idempotent. A set absorbs the same retry.
  3. 3. What does frozen<address> mean?

    A frozen value is serialized into one cell. You cannot update a single field of it, but you can use it inside a primary key or another collection.
  4. 4. Which is the safest use of a counter column?

    Increments are not idempotent, so retries can overcount. That is acceptable for statistics and unacceptable for money or stock.

Summary

  • Use text, decimal for money, uuid for ids and timeuuid when you need unique ids that sort by time.
  • Collections (list, set, map) are for small amounts of data. Sets and maps absorb repeated writes; list appends do not.
  • frozen stores a collection or UDT as a single cell, replaced as a whole. Only frozen values can be part of a primary key.
  • Counters can only be incremented, are not idempotent, and suit approximate statistics.
  • The stand-ins mimic these semantics; the CQL blocks show the real syntax but were not run here.

Next: Time-series and bucketing patterns.