dbt with Redshift
Redshift Architecture
Sort Key Strategy
Distribution Strategy
Detailed Explanation
What is Redshift + dbt?
Amazon Redshift is a fully managed, petabyte-scale data warehouse that provides powerful analytics capabilities.
Core Features
| Feature | Description |
|---|---|
| Columnar Storage | Optimized for analytics queries |
| MPP | Distribute queries across nodes |
| Distribution Keys | Optimize data distribution for joins |
| Sort Keys | Optimize data ordering for queries |
| Compression | Automatic data compression |
Distribution Styles
| Style | Behavior | Best For |
|---|---|---|
| EVEN | Round-robin distribution | Default / no join optimization |
| KEY | Hash-based on a column | Large fact tables with joins |
| ALL | Copy to every node | Small dimension tables |
Sort Key Types
- Compound â Multi-column sort with prefix matching
- Interleaved â Equal-weight multi-column sort
- Auto â System-managed sort key selection
Key Takeaway: Choose distribution keys based on your most frequent JOIN patterns. Use ALL distribution for small dimension tables to avoid shuffling.
Code Examples
Redshift Profile Configuration
# profiles.yml
my_profile:
target: dev
outputs:
dev:
type: redshift
host: my-cluster.xxxxxxxxxxxx.us-west-2.redshift.amazonaws.com
port: 5439
user: my_user
password: "{{ env_var('REDSHIFT_PASSWORD') }}"
dbname: analytics_dev
schema: dbt_dev
threads: 4
connect_timeout: 10
ra3_node: true
prod:
type: redshift
host: my-prod-cluster.xxxxxxxxxxxx.us-west-2.redshift.amazonaws.com
port: 5439
user: service_account
password: "{{ env_var('REDSHIFT_PASSWORD') }}"
dbname: analytics_prod
schema: public
threads: 8
connect_timeout: 30
ra3_node: true
Distribution Key Configuration
# models/marts/fct_orders.yml
version: 2
models:
- name: fct_orders
description: "Fact table for orders"
config:
materialized: incremental
unique_key: order_id
incremental_strategy: merge
dist_style: key
dist_key: customer_id
sort_type: compound
sort_key:
- order_date
- customer_id
post_hook:
- "vacuum sortkey order by order_date"
- "analyze"
Sort Key Configuration
-- models/marts/fct_events.sql
{{
config(
materialized='incremental',
unique_key='event_id',
incremental_strategy='merge',
dist_style='key',
dist_key='user_id',
sort_type='compound',
sort_key=['event_date', 'user_id', 'event_type']
)
}}
with events as (
select * from {{ ref('stg_events') }}
),
final as (
select
event_id,
user_id,
event_type,
event_timestamp,
cast(event_timestamp as date) as event_date,
event_properties,
current_timestamp() as updated_at
from events
)
select * from final
{% if is_incremental() %}
where event_date >= date_sub(
(select max(event_date) from {{ this }}),
interval 7 day
)
{% endif %}
ALL Distribution for Dimension Tables
-- models/marts/dim_customers.sql
{{
config(
materialized='table',
dist_style='all',
sort_type='compound',
sort_key=['customer_id']
)
}}
with customers as (
select * from {{ ref('stg_customers') }}
),
final as (
select
customer_id,
customer_name,
email,
segment,
current_timestamp() as updated_at
from customers
)
select * from final
Redshift-Specific Macros
-- macros/redshift/vacuum_table.sql
{% macro vacuum_table(table_name, sort_key=None) %}
{% if sort_key %}
vacuum sortkey order by {{ sort_key }} on {{ table_name }};
{% else %}
vacuum on {{ table_name }};
{% endif %}
{% endmacro %}
-- macros/redshift/analyze_table.sql
{% macro analyze_table(table_name) %}
analyze {{ table_name }};
{% endmacro %}
-- macros/redshift/grant_permissions.sql
{% macro grant_permissions(table_name, role='analytics_reader') %}
grant select on {{ table_name }} to role {{ role }};
{% endmacro %}
Workload Management Configuration
-- macros/redshift/create_wlm_queue.sql
{% macro create_wlm_queue(queue_name, memory_percent=40, concurrency=5) %}
-- Note: WLM configuration is typically done via AWS Console
-- This macro provides a template for documentation
/*
WLM Queue Configuration:
Queue: {{ queue_name }}
Memory: {{ memory_percent }}%
Concurrency: {{ concurrency }}
Query Timeout: 600 seconds
Use Cases:
- dbt runs: Use dedicated queue
- Ad-hoc queries: Use separate queue
- ETL jobs: Use high-memory queue
*/
{% endmacro %}
Optimized Redshift Model
-- models/marts/fct_orders_optimized.sql
{{
config(
materialized='incremental',
unique_key='order_id',
incremental_strategy='merge',
dist_style='key',
dist_key='customer_id',
sort_type='compound',
sort_key=['order_date', 'customer_id'],
post_hook=[
"{{ vacuum_table(this, 'order_date') }}",
"{{ analyze_table(this) }}"
]
)
}}
with orders as (
select * from {{ ref('stg_orders') }}
),
final as (
select
order_id,
customer_id,
order_date,
order_status,
amount,
current_timestamp() as updated_at
from orders
)
select * from final
{% if is_incremental() %}
where order_date >= date_sub(
(select max(order_date) from {{ this }}),
interval 7 day
)
{% endif %}
Performance Metrics
| Metric | Description | Target |
|---|---|---|
| Query Time | Average query execution | <10s |
| Vacuum Time | Time to vacuum tables | <5min |
| Analyze Time | Time to analyze tables | <1min |
| Storage Usage | Percentage of disk used | <70% |
| Query Queue Time | Time waiting in queue | <5s |
Best Practices
- Choose distribution keys wisely - Match join patterns
- Use compound sort keys - For prefix-matching queries
- Distribute dimension tables as ALL - For small tables
- Use vacuum - Reclaim space after deletes
- Analyze statistics - Keep query planner informed
- Monitor query performance - Use STL tables
- Use result caching - Cache frequent queries
- Implement workload management - Prioritize queries
See Also
- Performance Tuning â General optimization strategies
- dbt BigQuery â BigQuery partitioning and clustering
- dbt Snowflake â Snowflake warehouse optimization
- dbt Best Practices â Project structure and patterns
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions