everything-gemini 1.2.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/.github/ISSUE_TEMPLATE/bug_report.md +29 -0
  2. package/.github/ISSUE_TEMPLATE/feature_request.md +27 -0
  3. package/.github/ISSUE_TEMPLATE/subagent_proposal.md +29 -0
  4. package/.github/workflows/ci.yml +72 -1
  5. package/.github/workflows/release.yml +17 -2
  6. package/CHANGELOG.md +178 -0
  7. package/CONTRIBUTING.md +90 -4
  8. package/README.md +147 -23
  9. package/action.yml +35 -0
  10. package/agents/browser-qa.md +1 -1
  11. package/agents/database-migrator.md +26 -0
  12. package/agents/documentation-writer.md +27 -0
  13. package/agents/incident-responder.md +34 -0
  14. package/agents/performance-tuner.md +27 -0
  15. package/agents/platform-engineer.md +33 -0
  16. package/agents/release-engineer.md +34 -0
  17. package/bin/everything-gemini +1791 -142
  18. package/docs/COMMUNITY_SUBMISSIONS.md +88 -0
  19. package/docs/LAUNCH_KIT.md +138 -13
  20. package/docs/architecture/progressive-disclosure.md +3 -3
  21. package/docs/index.html +410 -40
  22. package/docs/launch-kit.md +163 -0
  23. package/examples/cli-workflows/demo_workflow.sh +15 -7
  24. package/examples/python-sdk/README.md +32 -5
  25. package/examples/python-sdk/documentation_audit_pipeline.py +83 -0
  26. package/examples/python-sdk/incident_triage_pipeline.py +170 -0
  27. package/examples/python-sdk/multi_agent_pipeline.py +95 -0
  28. package/examples/python-sdk/platform_provisioning_pipeline.py +193 -0
  29. package/examples/python-sdk/release_readiness_audit.py +144 -0
  30. package/hooks/secret-scrubber/hooks.json +16 -0
  31. package/hooks/secret-scrubber/scripts/scrub-secrets.sh +62 -0
  32. package/mcp/README.md +21 -0
  33. package/mcp/mcp_config.example.json +39 -0
  34. package/package.json +3 -1
  35. package/plugins/core/rules/core-practices.md +63 -4
  36. package/plugins/python-ai/rules/ai-agent-patterns.md +67 -4
  37. package/plugins/security-shield/rules/zero-trust.md +60 -4
  38. package/plugins/web-fullstack/rules/frontend-standards.md +74 -4
  39. package/rules/paradigms/security-hardened.md +53 -10
  40. package/rules/paradigms/tdd.md +65 -8
  41. package/scripts/install.ps1 +14 -0
  42. package/scripts/install.sh +15 -1
  43. package/scripts/validate.sh +103 -12
  44. package/skills/apache-kafka-streams/SKILL.md +152 -0
  45. package/skills/argo-workflows/SKILL.md +151 -0
  46. package/skills/axum-web-service/SKILL.md +159 -0
  47. package/skills/cilium-ebpf-networking/SKILL.md +145 -0
  48. package/skills/clickhouse-analytics/SKILL.md +128 -0
  49. package/skills/cloudflare-r2-object-storage/SKILL.md +143 -0
  50. package/skills/dbt-transformation/SKILL.md +179 -0
  51. package/skills/debezium-cdc/SKILL.md +166 -0
  52. package/skills/distributed-rate-limiting/SKILL.md +138 -0
  53. package/skills/duckdb-local-olap/SKILL.md +134 -0
  54. package/skills/fastapi-production/SKILL.md +157 -0
  55. package/skills/grpc-connect-rpc/SKILL.md +176 -0
  56. package/skills/langgraph-orchestrator/SKILL.md +144 -0
  57. package/skills/litellm-proxy-gateway/SKILL.md +154 -0
  58. package/skills/milvus-vector-clustering/SKILL.md +134 -0
  59. package/skills/nats-jetstream/SKILL.md +122 -0
  60. package/skills/open-telemetry-tracing/SKILL.md +151 -0
  61. package/skills/playwright-visual-regression/SKILL.md +124 -0
  62. package/skills/redis-cache-patterns/SKILL.md +159 -0
  63. package/skills/svelte-kit-architect/SKILL.md +190 -0
  64. package/skills/temporal-workflows/SKILL.md +158 -0
  65. package/skills/trpc-react-query/SKILL.md +169 -0
  66. package/skills/turborepo-monorepo/SKILL.md +199 -0
  67. package/skills/vault-secrets-management/SKILL.md +129 -0
  68. package/skills/vllm-inference/SKILL.md +144 -0
  69. package/skills/wasm-rust-optimizer/SKILL.md +130 -0
  70. package/templates/full-power/hooks.json +14 -0
  71. package/templates/full-power/mcp_config.json +47 -0
  72. package/templates/recommended/hooks.json +14 -0
  73. package/tests/cli.test.js +447 -0
@@ -0,0 +1,151 @@
1
+ ---
2
+ name: argo-workflows
3
+ description: >-
4
+ Architects, defines, and executes Kubernetes-native DAG workflows, artifact passing, container steps, retry strategies, and CronWorkflows using Argo Workflows.
5
+ ---
6
+
7
+ # Argo Workflows & Kubernetes-Native DAG Orchestration
8
+
9
+ This skill provides operational patterns for designing, testing, and deploying Kubernetes-native workflow orchestration via Argo Workflows, powering parallel data pipelines, machine learning training graphs, and automated batch processing.
10
+
11
+ ---
12
+
13
+ ## ⚡ Core Architecture & CRDs
14
+
15
+ 1. **`Workflow`**: Ephemeral, single-run execution specification.
16
+ 2. **`WorkflowTemplate`**: Reusable workflow definitions stored inside the Kubernetes cluster.
17
+ 3. **`CronWorkflow`**: Time-triggered recurring workflows (cron schedule).
18
+ 4. **DAGs vs Steps**: DAGs declare declarative dependency graphs (`dependencies: [taskA, taskB]`), whereas Steps declare sequential matrix execution.
19
+ 5. **Artifacts**: Input/output binary blobs, model weights, and logs backed by S3, GCS, or MinIO.
20
+
21
+ ---
22
+
23
+ ## 🏗️ Production DAG Workflow Specification (`workflow-dag.yaml`)
24
+
25
+ ```yaml
26
+ apiVersion: argoproj.io/v1alpha1
27
+ kind: Workflow
28
+ metadata:
29
+ generateName: ml-pipeline-dag-
30
+ namespace: argo
31
+ spec:
32
+ entrypoint: ml-pipeline
33
+ serviceAccountName: argo-workflow-executor
34
+ shutdown: "Stop" # Graceful termination support
35
+ onExit: pipeline-cleanup-handler
36
+
37
+ templates:
38
+ - name: ml-pipeline
39
+ dag:
40
+ tasks:
41
+ - name: ingest-data
42
+ template: data-ingestion-step
43
+ arguments:
44
+ parameters:
45
+ - name: dataset-version
46
+ value: "v2026.10"
47
+
48
+ - name: validate-schema
49
+ dependencies: [ingest-data]
50
+ template: schema-validator-step
51
+ arguments:
52
+ artifacts:
53
+ - name: raw-dataset
54
+ from: "{{tasks.ingest-data.outputs.artifacts.dataset}}"
55
+
56
+ - name: train-model
57
+ dependencies: [validate-schema]
58
+ template: model-training-step
59
+ arguments:
60
+ artifacts:
61
+ - name: validated-data
62
+ from: "{{tasks.validate-schema.outputs.artifacts.clean-dataset}}"
63
+
64
+ - name: data-ingestion-step
65
+ inputs:
66
+ parameters:
67
+ - name: dataset-version
68
+ container:
69
+ image: python:3.11-slim
70
+ command: [python, -c]
71
+ args: ["import json; open('/tmp/dataset.csv', 'w').write('id,score\\n1,0.95\\n')"]
72
+ outputs:
73
+ artifacts:
74
+ - name: dataset
75
+ path: /tmp/dataset.csv
76
+
77
+ - name: schema-validator-step
78
+ inputs:
79
+ artifacts:
80
+ - name: raw-dataset
81
+ path: /inputs/dataset.csv
82
+ container:
83
+ image: python:3.11-slim
84
+ command: [python, -c]
85
+ args: ["import shutil; shutil.copy('/inputs/dataset.csv', '/outputs/clean.csv')"]
86
+ outputs:
87
+ artifacts:
88
+ - name: clean-dataset
89
+ path: /outputs/clean.csv
90
+
91
+ - name: model-training-step
92
+ inputs:
93
+ artifacts:
94
+ - name: validated-data
95
+ path: /data/clean.csv
96
+ retryStrategy:
97
+ limit: "3"
98
+ retryPolicy: "Always"
99
+ backoff:
100
+ duration: "10s"
101
+ factor: 2
102
+ container:
103
+ image: python:3.11-slim
104
+ resources:
105
+ requests:
106
+ cpu: "2"
107
+ memory: "4Gi"
108
+ limits:
109
+ cpu: "4"
110
+ memory: "8Gi"
111
+ command: [python, -c]
112
+ args: ["print('Model trained successfully')"]
113
+
114
+ - name: pipeline-cleanup-handler
115
+ container:
116
+ image: alpine:latest
117
+ command: [sh, -c]
118
+ args: ["echo Pipeline finished with status: {{workflow.status}}"]
119
+ ```
120
+
121
+ ---
122
+
123
+ ## 🛠️ CLI Operations & Debugging Runbook
124
+
125
+ ```bash
126
+ # Submit a workflow and follow real-time execution
127
+ argo submit --watch workflow-dag.yaml -n argo
128
+
129
+ # List active and completed workflows
130
+ argo list -n argo
131
+
132
+ # Stream logs of a specific DAG task step
133
+ argo logs @latest -c main -n argo
134
+
135
+ # Resubmit a failed workflow with memoized step caching
136
+ argo resubmit --memoized @latest -n argo
137
+
138
+ # Terminate or suspend a runaway workflow
139
+ argo terminate @latest -n argo
140
+ ```
141
+
142
+ ---
143
+
144
+ ## 🛡️ Best Practices & Anti-Patterns
145
+
146
+ | Category | ❌ Anti-Pattern | ✅ Production Best Practice |
147
+ | :--- | :--- | :--- |
148
+ | **Artifacts** | Storing giant datasets directly inside pod disk | Use external artifact repositories (S3 / GCS) with lifecycle policies |
149
+ | **Retries** | Unbounded retries without exponential backoff | Set explicit `retryStrategy.limit` and exponential `backoff.factor` |
150
+ | **Resources** | Omitting CPU/Memory resource constraints | Always specify `requests` and `limits` to prevent node OOM crashes |
151
+ | **Secrets** | Hardcoding API keys or database URLs in YAML | Reference Kubernetes Secrets via `env.valueFrom.secretKeyRef` |
@@ -0,0 +1,159 @@
1
+ ---
2
+ name: axum-web-service
3
+ description: >-
4
+ Architects, builds, and optimizes production Rust web APIs using Axum, Tokio async runtime, Tower middlewares, type-safe state extractors, and SQLx connection pools.
5
+ ---
6
+
7
+ # Axum Web Service Architecture (Rust)
8
+
9
+ This skill guides engineering microservices with Axum—the high-throughput, ergonomic Rust web framework built on top of Tokio, Tower, and Hyper.
10
+
11
+ ---
12
+
13
+ ## ⚡ Core Patterns
14
+
15
+ ### 1. Application State & Router Composition (`main.rs`)
16
+
17
+ ```rust
18
+ use axum::{
19
+ extract::{Path, State},
20
+ http::StatusCode,
21
+ response::IntoResponse,
22
+ routing::{get, post},
23
+ Json, Router,
24
+ };
25
+ use sqlx::PgPool;
26
+ use std::{net::SocketAddr, sync::Arc};
27
+ use tower_http::{cors::CorsLayer, trace::TraceLayer};
28
+
29
+ #[derive(Clone)]
30
+ pub struct AppState {
31
+ pub db: PgPool,
32
+ pub redis: redis::aio::ConnectionManager,
33
+ }
34
+
35
+ #[tokio::main]
36
+ async fn main() -> Result<(), Box<dyn std::error::Error>> {
37
+ tracing_subscriber::fmt::init();
38
+
39
+ let db_pool = PgPool::connect(&std::env::var("DATABASE_URL")?).await?;
40
+ let redis_client = redis::Client::open(std::env::var("REDIS_URL")?)?;
41
+ let redis_mgr = redis_client.get_tokio_connection_manager().await?;
42
+
43
+ let shared_state = Arc::new(AppState {
44
+ db: db_pool,
45
+ redis: redis_mgr,
46
+ });
47
+
48
+ let app = Router::new()
49
+ .route("/healthz", get(|| async { StatusCode::OK }))
50
+ .nest("/api/v1", api_v1_router())
51
+ .layer(TraceLayer::new_for_http())
52
+ .layer(CorsLayer::permissive())
53
+ .with_state(shared_state);
54
+
55
+ let addr = SocketAddr::from(([0, 0, 0, 0], 8080));
56
+ let listener = tokio::net::TcpListener::bind(addr).await?;
57
+ tracing::info!("Listening on {}", addr);
58
+ axum::serve(listener, app).await?;
59
+
60
+ Ok(())
61
+ }
62
+ ```
63
+
64
+ ---
65
+
66
+ ### 2. Type-Safe Handlers with SQLx (`handlers/users.rs`)
67
+
68
+ Use Axum's compile-time extractors to ensure payload and state invariants before handler execution:
69
+
70
+ ```rust
71
+ use axum::{
72
+ extract::{Path, State},
73
+ Json,
74
+ };
75
+ use serde::{Deserialize, Serialize};
76
+ use std::sync::Arc;
77
+ use crate::{AppState, error::AppError};
78
+
79
+ #[derive(Deserialize)]
80
+ pub struct CreateUserPayload {
81
+ pub username: String,
82
+ pub email: String,
83
+ }
84
+
85
+ #[derive(Serialize)]
86
+ pub struct UserResponse {
87
+ pub id: i64,
88
+ pub username: String,
89
+ pub email: String,
90
+ }
91
+
92
+ pub async fn create_user(
93
+ State(state): State<Arc<AppState>>,
94
+ Json(payload): Json<CreateUserPayload>,
95
+ ) -> Result<Json<UserResponse>, AppError> {
96
+ // Compile-time verified query via SQLx
97
+ let user = sqlx::query_as!(
98
+ UserResponse,
99
+ r#"
100
+ INSERT INTO users (username, email)
101
+ VALUES ($1, $2)
102
+ RETURNING id, username, email
103
+ "#,
104
+ payload.username,
105
+ payload.email
106
+ )
107
+ .fetch_one(&state.db)
108
+ .await?;
109
+
110
+ Ok(Json(user))
111
+ }
112
+ ```
113
+
114
+ ---
115
+
116
+ ### 3. Unified RFC 7807 Error Envelope (`error.rs`)
117
+
118
+ Transform any internal database or validation failure into clean, typed JSON responses using `IntoResponse`:
119
+
120
+ ```rust
121
+ use axum::{
122
+ http::StatusCode,
123
+ response::{IntoResponse, Response},
124
+ Json,
125
+ };
126
+ use serde_json::json;
127
+
128
+ #[derive(thiserror::Error, Debug)]
129
+ pub enum AppError {
130
+ #[error("Database error: {0}")]
131
+ Database(#[from] sqlx::Error),
132
+ #[error("Resource not found")]
133
+ NotFound,
134
+ #[error("Validation failed: {0}")]
135
+ Validation(String),
136
+ }
137
+
138
+ impl IntoResponse for AppError {
139
+ fn into_response(self) -> Response {
140
+ let (status, detail) = match self {
141
+ AppError::NotFound => (StatusCode::NOT_FOUND, "The requested resource does not exist.".to_string()),
142
+ AppError::Validation(msg) => (StatusCode::BAD_REQUEST, msg),
143
+ AppError::Database(err) => {
144
+ tracing::error!("Internal DB error: {:?}", err);
145
+ (StatusCode::INTERNAL_SERVER_ERROR, "An internal server error occurred.".to_string())
146
+ }
147
+ };
148
+
149
+ let body = Json(json!({
150
+ "type": "https://errors.example.com",
151
+ "title": status.canonical_reason().unwrap_or("Error"),
152
+ "status": status.as_u16(),
153
+ "detail": detail
154
+ }));
155
+
156
+ (status, body).into_response()
157
+ }
158
+ }
159
+ ```
@@ -0,0 +1,145 @@
1
+ ---
2
+ name: cilium-ebpf-networking
3
+ description: >-
4
+ Cloud-native eBPF networking, Kubernetes CNI replacement, transparent mutual TLS (mTLS), L7 CiliumNetworkPolicies, and Hubble network observability. Use when securing cluster traffic, eliminating kube-proxy iptables bottlenecks, or debugging service mesh latency.
5
+ ---
6
+
7
+ # Cilium eBPF Networking & Security Architecture
8
+
9
+ A production runbook for deploying, configuring, and troubleshooting **Cilium eBPF**, high-performance Kubernetes networking, and deep packet observability with **Hubble**.
10
+
11
+ ---
12
+
13
+ ## 🎯 Architectural Advantages of eBPF
14
+
15
+ 1. **Bypasses iptables / IPVS Overhead**: Programs run directly in the Linux kernel network stack (`tc` / `xdp`), providing O(1) connection routing regardless of service count.
16
+ 2. **Kernel-Level Identity**: Enforces security policies based on cryptographically verified Kubernetes metadata and SPIFFE identities rather than volatile IP addresses.
17
+ 3. **Transparent Encryption**: Mutual TLS (mTLS) or WireGuard encryption negotiated dynamically at the kernel layer with zero application sidecars.
18
+ 4. **Hubble Observability**: Zero-overhead flow logging, DNS resolution tracking, and L7 HTTP/gRPC metrics without code instrumentation.
19
+
20
+ ---
21
+
22
+ ## 🚀 Helm Deployment (kube-proxy Replacement)
23
+
24
+ ```bash
25
+ helm repo add cilium https://helm.cilium.io/
26
+ helm repo update
27
+
28
+ helm install cilium cilium/cilium --version 1.16.0 \
29
+ --namespace kube-system \
30
+ --set kubeProxyReplacement=true \
31
+ --set k8sServiceHost=10.0.0.1 \
32
+ --set k8sServicePort=6443 \
33
+ --set routingMode=native \
34
+ --set autoDirectNodeRoutes=true \
35
+ --set bpf.masquerade=true \
36
+ --set encryption.enabled=true \
37
+ --set encryption.type=wireguard \
38
+ --set hubble.enabled=true \
39
+ --set hubble.relay.enabled=true \
40
+ --set hubble.ui.enabled=true \
41
+ --set hubble.metrics.enabled="{dns,drop,tcp,flow,port-distribution,icmp,httpV2:exemplars=true;labelsContext=source_ip\,source_namespace\,source_workload\,destination_ip\,destination_namespace\,destination_workload\,traffic_direction}"
42
+ ```
43
+
44
+ ---
45
+
46
+ ## 🛡️ L7 CiliumNetworkPolicy Specification
47
+
48
+ Enforce strict Zero-Trust boundaries allowing only authorized HTTP/gRPC methods between microservices:
49
+
50
+ ```yaml
51
+ apiVersion: "cilium.io/v2"
52
+ kind: CiliumNetworkPolicy
53
+ metadata:
54
+ name: order-service-l7-policy
55
+ namespace: production
56
+ spec:
57
+ endpointSelector:
58
+ matchLabels:
59
+ app: order-service
60
+ ingress:
61
+ - fromEndpoints:
62
+ - matchLabels:
63
+ app: api-gateway
64
+ toPorts:
65
+ - ports:
66
+ - port: "8080"
67
+ protocol: TCP
68
+ rules:
69
+ http:
70
+ - method: "POST"
71
+ path: "/v1/orders"
72
+ - method: "GET"
73
+ path: "/v1/orders/.*"
74
+ egress:
75
+ - toEndpoints:
76
+ - matchLabels:
77
+ app: payment-service
78
+ toPorts:
79
+ - ports:
80
+ - port: "8443"
81
+ protocol: TCP
82
+ rules:
83
+ http:
84
+ - method: "POST"
85
+ path: "/v1/charges"
86
+ - toFQDNs:
87
+ - matchName: "api.stripe.com"
88
+ toPorts:
89
+ - ports:
90
+ - port: "443"
91
+ protocol: TCP
92
+ ```
93
+
94
+ ---
95
+
96
+ ## 🔍 Hubble CLI Diagnostic Workflows
97
+
98
+ The Hubble CLI provides real-time kernel packet inspection:
99
+
100
+ ### 1. Tail Dropped Packets in Namespace
101
+
102
+ ```bash
103
+ hubble observe --namespace production --verdict DROP -f
104
+ ```
105
+
106
+ ### 2. Trace HTTP Latency & 5xx Status Errors
107
+
108
+ ```bash
109
+ hubble observe \
110
+ --namespace production \
111
+ --protocol http \
112
+ --http-status 5.. \
113
+ --output jsonpb | jq '{source: .flow.source.pod_name, dest: .flow.destination.pod_name, status: .flow.l7.http.code}'
114
+ ```
115
+
116
+ ### 3. Inspect DNS Queries and Lookup Failures
117
+
118
+ ```bash
119
+ hubble observe --namespace production --protocol dns
120
+ ```
121
+
122
+ ---
123
+
124
+ ## 📈 Prometheus Service Metrics Integration
125
+
126
+ Cilium exposes Prometheus metrics on port `9962` (agent) and `9965` (operator):
127
+
128
+ ```text
129
+ cilium_forward_count_total # Total packets forwarded through eBPF datapath
130
+ cilium_drop_count_total # Total packets dropped by policy or checksum failure
131
+ cilium_bpf_map_pressure # Map utilization (target: < 0.70 to avoid overflow)
132
+ hubble_flows_processed_total # Flow event processing rate
133
+ ```
134
+
135
+ ---
136
+
137
+ ## ⚠️ Troubleshooting & Production Checklist
138
+
139
+ 1. **BPF Map Pressure Alert**:
140
+ - Inspect active map sizing: `cilium-dbg bpf map list`.
141
+ - If `cilium_lb4_services_v2` exceeds 80%, increase `--set bpf.lbMapMax=65536`.
142
+ 2. **WireGuard Encryption Verification**:
143
+ - Run `cilium status --verbose` and confirm `Encryption: WireGuard [Node: OK, Pod: OK]`.
144
+ 3. **Kernel Version Compatibility**:
145
+ - Requires Linux Kernel >= 5.10 for full kube-proxy replacement, and >= 5.15 for transparent mTLS encryption.
@@ -0,0 +1,128 @@
1
+ ---
2
+ name: clickhouse-analytics
3
+ description: >-
4
+ Architects, models, and optimizes high-throughput ClickHouse OLAP analytical schemas, MergeTree table engines, real-time materialized views, and vector similarity search.
5
+ ---
6
+
7
+ # ClickHouse Analytics & Real-Time OLAP
8
+
9
+ This skill guides high-throughput schema modeling, query optimization, and real-time streaming ingestion on ClickHouse for analytics and vector retrieval.
10
+
11
+ ---
12
+
13
+ ## ⚡ Core Engine & Table Design
14
+
15
+ ### 1. Engine Selection Matrix
16
+
17
+ | Engine | Best For | Behavior |
18
+ | :--- | :--- | :--- |
19
+ | **`MergeTree`** | Default append-only timeseries | Base engine for fast parallel range scans and primary indexing. |
20
+ | **`ReplacingMergeTree`** | Deduplication & upserts | Replaces rows with matching sorting keys during background compaction. |
21
+ | **`SummingMergeTree`** | Real-time counter rollups | Automatically aggregates numeric columns with identical sorting keys. |
22
+ | **`AggregatingMergeTree`**| Pre-aggregated state metrics | Stores intermediate aggregate states (e.g. `uniqExactState`, `quantilesState`). |
23
+
24
+ ---
25
+
26
+ ### 2. Primary Key & Partitioning Strategy
27
+
28
+ In ClickHouse, the `ORDER BY` defines the sparse primary index (1 index mark every 8,192 rows). Order columns by ascending cardinality:
29
+
30
+ ```sql
31
+ CREATE TABLE analytics.events (
32
+ tenant_id UUID,
33
+ event_type LowCardinality(String),
34
+ user_id String,
35
+ properties JSON,
36
+ timestamp DateTime64(3, 'UTC')
37
+ ) ENGINE = MergeTree()
38
+ PARTITION BY toYYYYMM(timestamp)
39
+ ORDER BY (tenant_id, event_type, timestamp, user_id)
40
+ SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
41
+ ```
42
+
43
+ > **Rules:**
44
+ > 1. Never partition by high-cardinality fields (like `user_id` or `toDate(timestamp)`); keep partition counts under 1,000 to prevent metadata explosion.
45
+ > 2. Use `LowCardinality(String)` for strings with < 10,000 distinct values (e.g., country codes, event names) for dictionary encoding.
46
+
47
+ ---
48
+
49
+ ## 🔄 Real-Time Ingestion with Kafka & Materialized Views
50
+
51
+ Stream data continuously from Apache Kafka directly into optimized storage tables using pipe tables and materialized views:
52
+
53
+ ```sql
54
+ -- 1. Kafka Queue Engine
55
+ CREATE TABLE analytics.kafka_events_queue (
56
+ raw_payload String
57
+ ) ENGINE = Kafka
58
+ SETTINGS kafka_broker_list = 'kafka:9092',
59
+ kafka_topic_list = 'app-events',
60
+ kafka_group_name = 'clickhouse-consumer',
61
+ kafka_format = 'JSONAsString';
62
+
63
+ -- 2. Destination Storage Table
64
+ CREATE TABLE analytics.events_store (
65
+ event_id UUID,
66
+ event_name LowCardinality(String),
67
+ payload JSON,
68
+ created_at DateTime DEFAULT now()
69
+ ) ENGINE = MergeTree()
70
+ ORDER BY (event_name, created_at);
71
+
72
+ -- 3. Materialized View Pipe
73
+ CREATE MATERIALIZED VIEW analytics.mv_kafka_to_events TO analytics.events_store AS
74
+ SELECT
75
+ JSONExtract(raw_payload, 'id', 'UUID') AS event_id,
76
+ JSONExtract(raw_payload, 'type', 'LowCardinality(String)') AS event_name,
77
+ raw_payload AS payload,
78
+ now() AS created_at
79
+ FROM analytics.kafka_events_queue;
80
+ ```
81
+
82
+ ---
83
+
84
+ ## 🚀 High-Performance Query Optimization
85
+
86
+ ### 1. Leverage `PREWHERE` for Selective Filters
87
+ `PREWHERE` reads filtered columns first and only fetches remaining requested columns for matching rows:
88
+
89
+ ```sql
90
+ SELECT
91
+ user_id,
92
+ count() AS total_events,
93
+ quantile(0.95)(JSONExtractFloat(properties, 'latency_ms')) AS p95_latency
94
+ FROM analytics.events
95
+ PREWHERE tenant_id = 'a3bb189e-8bf9-4888-9912-abcdef012345'
96
+ AND timestamp >= now() - INTERVAL 24 HOUR
97
+ WHERE event_type = 'api_request'
98
+ GROUP BY user_id
99
+ ORDER BY total_events DESC
100
+ LIMIT 50;
101
+ ```
102
+
103
+ ### 2. Approximate Aggregations for Massive Scale
104
+ - Use `uniqCombined64(user_id)` or `uniqHLL12(user_id)` instead of `uniqExact()` when calculating HyperLogLog DAU/MAU across hundreds of millions of events (~10x faster, <1% error).
105
+
106
+ ---
107
+
108
+ ## 🧠 Vector Similarity Search in ClickHouse
109
+
110
+ ClickHouse natively computes high-dimensional vector distances:
111
+
112
+ ```sql
113
+ CREATE TABLE analytics.article_embeddings (
114
+ id UUID,
115
+ title String,
116
+ embedding Array(Float32),
117
+ INDEX idx_emb embedding TYPE vector_similarity('hnsw', 'cosineDistance') GRANULARITY 1
118
+ ) ENGINE = MergeTree()
119
+ ORDER BY id;
120
+
121
+ -- Retrieve Top-K Nearest Neighbors
122
+ SELECT
123
+ title,
124
+ cosineDistance(embedding, [0.021, -0.145, 0.891, ...]) AS score
125
+ FROM analytics.article_embeddings
126
+ ORDER BY score ASC
127
+ LIMIT 10;
128
+ ```