> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/temporalio/temporal/llms.txt
> Use this file to discover all available pages before exploring further.

# Namespaces

> Namespace isolation, multi-tenancy, and management in Temporal Server

# Namespaces

Namespaces provide isolated execution environments within a Temporal cluster. Each namespace has its own workflows, activities, task queues, and configuration, enabling secure multi-tenancy and organizational separation.

## Namespace Fundamentals

A namespace is the fundamental isolation boundary in Temporal:

<CardGroup cols={2}>
  <Card title="Isolation" icon="shield">
    Workflows in one namespace cannot directly interact with workflows in another namespace. Complete data isolation.
  </Card>

  <Card title="Configuration" icon="gear">
    Each namespace has independent retention, archival, replication, and search attribute settings.
  </Card>

  <Card title="Multi-Tenancy" icon="users">
    Different teams, customers, or environments can share a cluster safely using separate namespaces.
  </Card>

  <Card title="Resource Limits" icon="gauge">
    Rate limits, quotas, and visibility can be configured per-namespace.
  </Card>
</CardGroup>

## Namespace Structure

Each namespace contains:

```go theme={null}
// From common/namespace/namespace.go
type Namespace struct {
    info          *persistencespb.NamespaceInfo
    config        *persistencespb.NamespaceConfig
    configVersion int64
    notificationVersion int64
    
    customSearchAttributesMapper CustomSearchAttributesMapper
    replicationResolver          ReplicationResolver
}

type NamespaceInfo struct {
    Id          string                    // Unique namespace ID (UUID)
    Name        string                    // User-visible namespace name
    State       enumspb.NamespaceState   // Registered, Deprecated, Deleted
    Description string
    Owner       string
    Data        map[string]string         // Custom key-value metadata
}
```

### Namespace ID vs Name

<Accordion title="Namespace ID">
  **Type**: UUID string (e.g., `"a1b2c3d4-e5f6-7890-abcd-ef1234567890"`)

  **Characteristics**:

  * Permanent and immutable
  * Used internally for all operations
  * Workflows/history keyed by namespace ID
  * Survives namespace renames
</Accordion>

<Accordion title="Namespace Name">
  **Type**: String (e.g., `"my-application"`, `"production"`, `"customer-acme"`)

  **Characteristics**:

  * User-visible, mutable (can be renamed)
  * Used in APIs and SDKs
  * Resolved to namespace ID by server
  * Must be unique within cluster
</Accordion>

## Namespace States

Namespaces transition through several states:

<Steps>
  <Step title="Registered (Active)">
    Normal operational state. Workflows can be started, workers can poll, all operations permitted.
  </Step>

  <Step title="Deprecated">
    Soft-deleted state. New workflows cannot be started, but existing workflows continue and can complete. Used for graceful wind-down.
  </Step>

  <Step title="Deleted">
    Hard-deleted state. Namespace cannot be used. Data retained per retention policy, then cleaned up.
  </Step>
</Steps>

```go theme={null}
func (ns *Namespace) State() enumspb.NamespaceState {
    if ns.info == nil {
        return enumspb.NAMESPACE_STATE_UNSPECIFIED
    }
    return ns.info.State
}
```

## Namespace Configuration

Each namespace has extensive configuration options:

### Retention Policy

```go theme={null}
type NamespaceConfig struct {
    // How long to keep workflow history after completion
    WorkflowExecutionRetentionTtl *durationpb.Duration  // e.g., 7 days, 30 days, 90 days
    
    // Bad binary checksums (for detecting bad deployments)
    BadBinaries *namespacepb.BadBinaries
}
```

<Warning>
  After retention period expires, workflow history is deleted. Choose retention based on compliance, debugging needs, and storage costs.
</Warning>

### Archival Configuration

Namespaces can archive workflow histories to long-term storage:

<Accordion title="History Archival">
  ```go theme={null}
  type ArchivalConfigState struct {
      State enumspb.ArchivalState  // Enabled or Disabled
      URI   string                  // Storage location (s3://bucket, gs://bucket)
  }

  func (ns *Namespace) HistoryArchivalState() ArchivalConfigState {
      return ArchivalConfigState{
          State: ns.config.HistoryArchivalState,
          URI:   ns.config.HistoryArchivalUri,
      }
  }
  ```

  **Supported Backends**:

  * Amazon S3 (`s3://bucket/prefix`)
  * Google Cloud Storage (`gs://bucket/prefix`)
  * Local filesystem (`file:///path`)

  **Use Cases**: Compliance, audit trails, long-term debugging
</Accordion>

<Accordion title="Visibility Archival">
  Separate from history archival, archives visibility records (workflow metadata).

  ```go theme={null}
  func (ns *Namespace) VisibilityArchivalState() ArchivalConfigState {
      return ArchivalConfigState{
          State: ns.config.VisibilityArchivalState,
          URI:   ns.config.VisibilityArchivalUri,
      }
  }
  ```
</Accordion>

### Custom Search Attributes

Namespaces can define custom search attributes for workflow search:

```go theme={null}
type CustomSearchAttributesMapper struct {
    fieldToAlias map[string]string  // Internal field -> user alias
    aliasToField map[string]string  // User alias -> internal field
}

type NamespaceConfig struct {
    CustomSearchAttributeAliases map[string]string
}
```

<Tip>
  Use search attributes to make workflows searchable by business-relevant fields like customer ID, order number, or status.
</Tip>

## Namespace Replication

For multi-cluster deployments, namespaces can be replicated:

```go theme={null}
type ReplicationPolicy int

const (
    // Single cluster - no replication
    ReplicationPolicyOneCluster ReplicationPolicy = 0
    
    // Multi-cluster - workflows replicated
    ReplicationPolicyMultiCluster ReplicationPolicy = 1
)
```

### Global Namespaces

<Accordion title="Global Namespace Features">
  **Active-Passive Replication**: One cluster is active (handles writes), others are passive (replicate).

  **Failover**: Can change which cluster is active, enabling disaster recovery.

  **Cross-Cluster Visibility**: View workflows from any cluster.

  **Use Cases**: Business continuity, disaster recovery, global presence.
</Accordion>

```go theme={null}
type ReplicationResolver interface {
    ReplicationState() enumspb.ReplicationState
    ActiveClusterName(businessID string) string
    ClusterNames(businessID string) []string
}

func (ns *Namespace) IsOnCluster(clusterName string) bool {
    for _, cluster := range ns.ClusterNames(EmptyBusinessID) {
        if cluster == clusterName {
            return true
        }
    }
    return false
}
```

## Namespace Registry

The server maintains an in-memory cache of all namespaces:

### Namespace Cache

<Steps>
  <Step title="Load from database">
    On startup, all namespace metadata loaded from persistence
  </Step>

  <Step title="Cache in memory">
    Namespace objects cached by ID and name for fast lookup
  </Step>

  <Step title="Watch for changes">
    Background process polls for namespace updates
  </Step>

  <Step title="Refresh cache">
    When namespace created/updated, cache entry refreshed
  </Step>
</Steps>

<Note>
  Cache refresh has eventual consistency. Namespace changes propagate to all server instances within seconds.
</Note>

## Namespace Sharding

While namespaces provide logical isolation, workflows are physically distributed:

```mermaid theme={null}
graph TB
    subgraph "Namespace: production"
        W1[Workflow 1]
        W2[Workflow 2]
        W3[Workflow 3]
    end
    
    subgraph "Namespace: staging"
        W4[Workflow 4]
        W5[Workflow 5]
    end
    
    subgraph "History Service Shards"
        S1[Shard 1]
        S2[Shard 2]
        S3[Shard 3]
        S4[Shard 4]
    end
    
    W1 --> S1
    W2 --> S3
    W3 --> S2
    W4 --> S4
    W5 --> S1
```

* **Workflows hashed across shards** by (Namespace ID, Workflow ID)
* **Multiple namespaces per shard** - shards not dedicated to namespaces
* **Enables scale** - even single namespace can use all shards

## Namespace Operations

### Creating Namespaces

```bash theme={null}
# Using tctl
tctl namespace register \
  --name my-namespace \
  --description "My application namespace" \
  --retention 7d

# Using Temporal Cloud
# Done via Web UI or tcld CLI
```

### Updating Namespaces

```bash theme={null}
# Update retention
tctl namespace update \
  --name my-namespace \
  --retention 30d

# Enable archival
tctl namespace update \
  --name my-namespace \
  --history-archival-state enabled \
  --history-uri "s3://my-bucket/temporal-archive"
```

### Describing Namespaces

```bash theme={null}
tctl namespace describe --name my-namespace
```

## Namespace Best Practices

<CardGroup cols={2}>
  <Card title="One Namespace Per Environment" icon="layer-group">
    Use separate namespaces for dev, staging, production. Prevents accidental cross-environment issues.
  </Card>

  <Card title="Namespace Per Customer" icon="user">
    For SaaS applications, use one namespace per customer for isolation and resource control.
  </Card>

  <Card title="Meaningful Names" icon="tag">
    Use descriptive names like `myapp-prod`, `customer-acme`, not generic names like `ns1`.
  </Card>

  <Card title="Document Ownership" icon="file-lines">
    Use description and metadata fields to track which team owns each namespace.
  </Card>
</CardGroup>

### Anti-Patterns

<Warning>
  **Don't create namespaces per workflow type**: Namespaces are heavyweight. Use task queues for routing different workflow types.
</Warning>

<Warning>
  **Don't over-provision namespaces**: Each namespace adds overhead. Prefer fewer namespaces with task queue routing.
</Warning>

## Namespace Limits and Quotas

Namespaces can have rate limits:

* **RPS limits**: Max requests per second for operations
* **Worker limits**: Max concurrent pollers per task queue
* **Workflow limits**: Max concurrent workflows
* **Visibility limits**: Max list/query rate

<Note>
  Limits configured via dynamic configuration or Temporal Cloud settings. Protects cluster from runaway workloads.
</Note>

## Namespace Security

Namespace-level security controls:

### Authorization

* **API key per namespace** (Temporal Cloud)
* **mTLS certificates** can be scoped to namespaces
* **RBAC policies** can restrict access to specific namespaces

### Audit Logging

* **Audit logs** track all namespace operations
* **Who created/modified** namespace
* **What changed** in configuration

## Namespace Observability

Key metrics per namespace:

* **Workflow Start Rate**: Workflows started per second
* **Workflow Completion Rate**: Workflows completed per second
* **Open Workflows**: Currently executing workflows
* **Task Queue Backlog**: Pending tasks across all task queues
* **Error Rates**: Failed workflows, activities, tasks

```go theme={null}
// Metrics are tagged with namespace name
metricsHandler.WithTags(metrics.NamespaceTag(namespace.Name().String()))
```

## Default Namespace

Each cluster has a `default` namespace:

* **Created automatically** on cluster bootstrap
* **Used if no namespace specified** in SDK clients (for development)
* **Not special otherwise** - same capabilities as any namespace

<Tip>
  Don't use `default` namespace for production. Create dedicated namespaces with appropriate configuration.
</Tip>

## Related Concepts

* [Task Queues](/concepts/task-queues) - Scoped within namespaces
* [Workflows](/concepts/workflows) - Belong to a namespace
* [Workers](/concepts/workers) - Poll specific namespace's task queues
