> ## Documentation Index
> Fetch the complete documentation index at: https://docs.go-mizu.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Overview

> Real-time WebSocket communication with topic-based pub/sub

The `live` package provides low-latency real-time message delivery over WebSocket with topic-based publish/subscribe. It's designed as a transport layer for instant updates: chat, notifications, collaborative editing, real-time dashboards, and more.

## What is Real-time Communication?

In traditional HTTP, the browser sends a request and waits for a response. For new data, you must make another request (polling).

**Traditional HTTP:**

```
Client: "Give me messages"    →    Server: Returns messages
Client: (waits...)
Client: "Any new messages?"   →    Server: Returns messages
```

With WebSockets, the connection stays open. Either side can send messages anytime.

**WebSocket:**

```
Client: "Connect"             →    Server: Connected!
Server: "New message!"        →    Client: Receives instantly
Server: "Another message!"    →    Client: Receives instantly
Client: "I'm typing..."       →    Server: Receives instantly
```

## Design Principles

| Principle       | Description                             |
| --------------- | --------------------------------------- |
| Transport-only  | Moves messages, doesn't interpret state |
| Best-effort     | No durability or replay guarantees      |
| Topic-based     | Scalable, simple pub/sub routing        |
| Opaque payloads | Your app defines message schemas        |
| Minimal surface | Few types, predictable behavior         |

## Architecture

```
                          ┌─────────────────────┐
                          │     Live Server     │
                          │                     │
Clients                   │  ┌───────────────┐  │
  │                       │  │   Sessions    │  │
  │  WebSocket            │  │               │  │
  ├──────────────────────▶│  │  Session A    │  │
  │                       │  │  Session B    │  │
  │  WebSocket            │  │  Session C    │  │
  ├──────────────────────▶│  │               │  │
  │                       │  └───────────────┘  │
  │  WebSocket            │         │          │
  ├──────────────────────▶│         │          │
  │                       │  ┌──────▼──────┐   │
                          │  │   Topics    │   │
                          │  │             │   │
                          │  │ "chat:room1"│   │
                          │  │ "user:123"  │   │
                          │  │ "global"    │   │
                          │  │             │   │
                          │  └─────────────┘   │
                          │                     │
                          └─────────────────────┘
```

1. **Clients connect** via WebSocket
2. **Sessions created** for each connection
3. **Server subscribes sessions** to topics
4. **Messages published** to topics
5. **All subscribers** receive the message

## Core Concepts

### Server

The Server manages WebSocket connections and pub/sub routing.

```go theme={null}
import "github.com/go-mizu/mizu/live"

server := live.New(live.Options{
    OnAuth: func(ctx context.Context, r *http.Request) (any, error) {
        // Authenticate connection
        return userID, nil
    },
})
```

### Session

A Session represents one WebSocket connection. Each has:

* Unique ID
* Optional value from authentication
* Send queue for outgoing messages

### Message

Messages have a topic and data:

```go theme={null}
type Message struct {
    Topic string          `json:"topic,omitempty"`
    Data  json.RawMessage `json:"data,omitempty"`
}
```

### Topics

Topics are named channels. Sessions subscribe to topics they care about. When you publish to a topic, all subscribers receive the message.

```go theme={null}
// Subscribe session to topic
server.Subscribe(session, "chat:room1")

// Publish to all subscribers
server.Publish("chat:room1", []byte(`{"text":"Hello!"}`))
```

## Quick Example

**Server (Go):**

```go theme={null}
package main

import (
    "context"
    "encoding/json"
    "net/http"

    "github.com/go-mizu/mizu"
    "github.com/go-mizu/mizu/live"
)

func main() {
    server := live.New(live.Options{
        OnAuth: func(ctx context.Context, r *http.Request) (any, error) {
            userID := r.URL.Query().Get("user")
            if userID == "" {
                return nil, fmt.Errorf("user required")
            }
            return userID, nil
        },
        OnMessage: func(ctx context.Context, s *live.Session, topic string, data []byte) {
            // Handle incoming messages
            if topic == "subscribe" {
                var req struct{ Topic string `json:"topic"` }
                json.Unmarshal(data, &req)
                server.Subscribe(s, req.Topic)
            } else if topic == "chat" {
                // Broadcast to all in chat
                server.Publish("chat:general", data)
            }
        },
        OnClose: func(s *live.Session, err error) {
            log.Printf("Session %s closed: %v", s.ID(), err)
        },
    })

    app := mizu.New()
    app.Get("/ws", mizu.Compat(server.Handler()))
    app.Listen(":8080")
}
```

**Client (JavaScript):**

```javascript theme={null}
const ws = new WebSocket('ws://localhost:8080/ws?user=alice');

ws.onmessage = (event) => {
    const msg = JSON.parse(event.data);
    console.log(`[${msg.topic}]`, msg.data);
};

// Subscribe to a topic
ws.send(JSON.stringify({topic: 'subscribe', data: {topic: 'chat:general'}}));

// Send a chat message
ws.send(JSON.stringify({topic: 'chat', data: {text: 'Hello!'}}));
```

## When to Use Live

**Use Live when:**

* You need instant updates (\< 100ms latency)
* Multiple clients need to see the same data
* Building interactive features (chat, gaming)
* Pushing data to clients (notifications)

**Consider alternatives when:**

* Updates are infrequent (use polling or SSE)
* You need message durability (use sync package)
* Building a simple REST API

## What's Next?

1. **[Quick Start](/view/live-quick-start)** - Build your first live feature
2. **[Server](/view/live-server)** - All server options explained
3. **[Sessions](/view/live-sessions)** - Connection lifecycle
4. **[Pub/Sub](/view/live-pubsub)** - Topic patterns and publishing
