🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Building a Data Lake on GCP with GCS and BigQuery

đŸŸĸ Free Lesson

Building a Data Lake on GCP with GCS and BigQuery

Data Lake Architecture on GCPBronze LayerRaw Data in GCSSilver LayerCleansed DataGold LayerBusiness DataBigQueryAnalytics & ReportingLookerBI & VisualizationLifecycle RulesCost OptimizationObject VersioningData ProtectionExternal TablesBigQuery IntegrationAuthorized ViewsData Access Control

What You'll Learn

  • 1Explain why a lake stores raw data and defers schema decisions to read time
  • 2Design bucket prefixes and lifecycle rules that cut storage cost without breaking queries
  • 3Choose between external tables, materialized copies and views for a given access pattern
  • 4Protect a lake against deletion with versioning, retention and authorized views

Why Raw Data Has to Be Kept

A warehouse answers questions you anticipated when you defined the schema. A lake exists for the questions you did not anticipate, which is why the first copy of every payload lands unmodified in Cloud Storage and the interpretation happens later. A payment webhook that starts sending a new field next month is a schema change the lake absorbs for free: the new field is simply present in the next object, and any downstream table that cares can be rebuilt. The same event written straight into a rigid warehouse table would need a migration, a backfill and a coordinated release.

The trade is that reading becomes the expensive part. Objects in Cloud Storage have no statistics, no partition pruning and no query optimizer, so something has to impose structure before analysts touch the data. That something is a layered path from raw to curated, plus a query engine that can be pointed at files directly. On GCP the pieces are Cloud Storage for the objects, BigQuery external tables for schema-on-read access, BigQuery native tables for anything queried repeatedly, and Dataplex for the catalog, quality rules and lineage that stop the lake becoming a swamp. Cost behaves differently too: storing a terabyte of Parquet in Standard class runs about twenty cents a month, while scanning it through an external table bills on the bytes processed rather than on storage, so the design question is always how often a given object will be read.

Data Lake Architecture

A data lake is a centralized repository for storing structured, semi-structured, and unstructured data at any scale. On GCP, Cloud Storage serves as the foundation for data lakes. The medallion layout shown above separates three guarantees rather than three teams: bronze preserves exactly what arrived so the pipeline can always be replayed, silver applies validation and de-duplication so consumers stop re-implementing them, and gold holds the aggregates a dashboard reads. Each layer is only as trustworthy as the layer before it, which is why quality checks belong at the boundary between them rather than inside a report.

Data Lake Layers

Bronze Layer (Raw):

  • Original data in native format
  • Immutable, append-only
  • Schema-on-read
  • Historical archive

Silver Layer (Cleansed):

  • Validated and cleansed data
  • Standardized formats
  • Deduplicated
  • Enriched with metadata

Gold Layer (Business):

  • Business-ready datasets
  • Aggregated and transformed
  • Optimized for analytics
  • Curated for specific use cases

Bucket Structure

Hierarchical Bucket Design

Prefixes are the only indexing mechanism a bucket has, so their design is a schema decision. Keep one bucket per environment rather than one per team, because cross-bucket IAM, lifecycle rules and dual-region settings then apply uniformly, and grant access at the prefix level where isolation is genuinely needed. The path that follows carries the layer, the domain, the table and then a time hierarchy, and every downstream tool parses the same convention: ingestion writes with a timestamp suffix, compaction rewrites many small objects into fewer large ones under a curated prefix, and readers filter on the date prefix so a daily job scans one directory instead of the whole bucket.

Listing performance and cost scale with the number of objects sharing a prefix, so a path that appends an hour and a minute keeps directory listings in the low thousands even when the bucket holds hundreds of millions of objects. Object naming should include an ingest timestamp or a batch identifier so that two runs of the same job cannot collide, and file sizes should be brought into the hundred megabyte to one gigabyte range by compaction. Small files are the classic lake tax: each object carries request overhead, each one is a separate read in a query plan, and a day written as forty thousand twenty kilobyte files scans far more slowly than the same bytes in forty files.

# Create bucket structure
gsutil mb -l us-central1 -c STANDARD gs://my-data-lake

# Create folder structure
gsutil mkdir gs://my-data-lake/bronze/raw/sales/2024/01/15
gsutil mkdir gs://my-data-lake/bronze/raw/sales/2024/01/16
gsutil mkdir gs://my-data-lake/silver/cleansed/sales
gsutil mkdir gs://my-data-lake/gold/curated/sales_daily_summary
gsutil mkdir gs://my-data-lake/looker/reports

Bucket Naming Conventions

Path Naming Patterns

python
# Path naming conventions
path_patterns = {
    'date_partitioned': 'gs://bucket/bronze/raw/{domain}/{yyyy}/{mm}/{dd}/',
    'hourly_partitioned': 'gs://bucket/bronze/raw/{domain}/{yyyy}/{mm}/{dd}/{hh}/',
    'monthly_partitioned': 'gs://bucket/silver/cleansed/{domain}/{yyyy}/{mm}/',
    'versioned': 'gs://bucket/gold/curated/{domain}/v{version}/',
    'archived': 'gs://bucket/archive/{domain}/{yyyy}/{mm}/{dd}/',
}

# Example paths
paths = {
    'sales_data': 'gs://my-data-lake/bronze/raw/sales/2024/01/15/',
    'user_events': 'gs://my-data-lake/bronze/raw/events/2024/01/15/10/',
    'daily_summary': 'gs://my-data-lake/gold/curated/sales_daily_summary/2024/01/',
}

Lifecycle Rules

Lifecycle rules automatically transition or delete objects based on age or other criteria, and they run server side at no charge. The economics are driven as much by minimum storage durations and retrieval fees as by the monthly rate, so a rule that moves data to a cold class sooner than the minimum duration is charged as if the minimum had been met.

Storage classPrice per GB-monthMinimum durationRetrieval feeTypical lake use
Standard2.0 centsNoneNoneBronze files under 30 days
Nearline1.0 cent30 days1 cent per GBSilver exports read monthly
Coldline0.4 cents90 days2 cents per GBGold history read quarterly
Archive0.12 cents365 days5 cents per GBRegulatory retention copies
AutoclassFalls with ageNoneNoneBronze objects nobody reads

Autoclass deserves a specific mention because it inverts the manual rule: it watches object access and moves untouched objects towards colder storage automatically, returning them to Standard when they are read again, which suits bronze where a handful of days are hot and the rest are never touched. Two safety rules apply to every lifecycle configuration. Never attach a delete rule to a prefix that holds the only copy of source data, and never set a transition rule on silver or gold without confirming that the reader, usually an external table or a scheduled job, is willing to pay the retrieval fee and the extra latency.

Cost Optimization Rules

Cost control in a lake is mostly about never paying twice for the same bytes. Three levers matter in order of effect: compression and format, because columnar Parquet with snappy compression routinely shrinks JSON by a factor of five to ten and queries then read fewer blocks; retention, because a bronze copy that is replayable from the source rarely needs to live longer than a few quarters; and class, because moving untouched objects down a tier cuts the monthly rate without touching availability. The configuration below encodes all three in one lifecycle document, with bronze transitioning at thirty, ninety and three hundred and sixty five days, silver following later, and a delete rule only on the raw prefix that the pipeline can regenerate.

# Create lifecycle configuration
cat > lifecycle.json << EOF
{
  "rule": [
    {
      "action": {"type": "SetStorageClass", "storageClass": "NEARLINE"},
      "condition": {"age": 30, "matchesPrefix": ["bronze/"]}
    },
    {
      "action": {"type": "SetStorageClass", "storageClass": "COLDLINE"},
      "condition": {"age": 90, "matchesPrefix": ["bronze/"]}
    },
    {
      "action": {"type": "SetStorageClass", "storageClass": "ARCHIVE"},
      "condition": {"age": 365, "matchesPrefix": ["bronze/"]}
    },
    {
      "action": {"type": "Delete"},
      "condition": {"age": 730, "matchesPrefix": ["bronze/raw/"]}
    },
    {
      "action": {"type": "SetStorageClass", "storageClass": "NEARLINE"},
      "condition": {"age": 60, "matchesPrefix": ["silver/"]}
    },
    {
      "action": {"type": "SetStorageClass", "storageClass": "COLDLINE"},
      "condition": {"age": 180, "matchesPrefix": ["silver/"]}
    }
  ]
}
EOF

# Apply lifecycle rules
gsutil lifecycle set lifecycle.json gs://my-data-lake

Lifecycle Rule Types

python
# Common lifecycle rule patterns
lifecycle_rules = {
    'transition_to_nearline': {
        'action': {'type': 'SetStorageClass', 'storageClass': 'NEARLINE'},
        'condition': {'age': 30}
    },
    'transition_to_coldline': {
        'action': {'type': 'SetStorageClass', 'storageClass': 'COLDLINE'},
        'condition': {'age': 90}
    },
    'transition_to_archive': {
        'action': {'type': 'SetStorageClass', 'storageClass': 'ARCHIVE'},
        'condition': {'age': 365}
    },
    'delete_old_data': {
        'action': {'type': 'Delete'},
        'condition': {'age': 730}
    },
    'abort_incomplete_multipart': {
        'action': {'type': 'AbortIncompleteMultipartUpload'},
        'condition': {'age': 7}
    }
}

# Apply lifecycle to specific prefixes
for prefix in ['bronze/', 'silver/', 'gold/']:
    bucket_name = f'gs://my-data-lake/{prefix}'
    print(f'Applying lifecycle to {bucket_name}')

Object Versioning

Object versioning protects against accidental deletion and provides data recovery capabilities. Once enabled, overwriting an object creates a new version and deleting it only marks the current version as a noncurrent one, so a mistaken gsutil rm -r on a curated prefix becomes a restore rather than an incident. Versioning changes the cost model: every noncurrent version is billed at its own storage rate and counts against the same lifecycle rules, which is why the versioned lifecycle pattern below deletes noncurrent versions after a year while leaving the live object alone. Pair versioning with a retention policy on the gold prefix so that even an administrator with delete permission cannot remove protected objects before the period expires, and note that a dual-region bucket keeps both versions across two regions in the same geography, which is what makes the restore survive a regional outage rather than merely a human error.

Enabling Versioning

# Enable versioning on bucket
gsutil versioning set on gs://my-data-lake

# Check versioning status
gsutil versioning get gs://my-data-lake

# List object versions
gsutil ls -la gs://my-data-lake/bronze/raw/sales/

Versioning Best Practices

python
# Versioning configuration
versioning_config = {
    'enabled': True,
    'metadata': 'preserve',
    'temporary_holds': True,
    'object_retention': True
}

# Lifecycle rules for versioned objects
versioned_lifecycle = {
    'rule': [
        {
            'action': {'type': 'Delete'},
            'condition': {
                'age': 365,
                'isLive': False  # Only delete non-current versions
            }
        },
        {
            'action': {'type': 'Delete'},
            'condition': {
                'age': 90,
                'isLive': True  # Keep current versions for 90 days
            }
        }
    ]
}

BigQuery External Tables

External tables let BigQuery read objects in Cloud Storage without copying them, which makes them the cheapest way to explore a bronze prefix and the most expensive way to run the same query four hundred times. There is no storage charge for the data behind the table because the bytes live in the bucket, but every query pays for the bytes it processes, and a scan of uncompressed JSON costs far more than the same rows in Parquet because BigQuery reads whole columns of a columnar file and skips the rest. The practical rule is a three stage path: point an external table at the raw prefix on day one, promote the dataset to a native table once a query pattern repeats, and keep the external table only for ad hoc archaeology on data nobody serves.

Format choice reinforces the same decision. Parquet and ORC carry statistics and column projection, so predicates prune files before they are read; CSV and JSON must be parsed in full, which is why they are acceptable for a first look and wrong for a dashboard. Compression is applied by the writer rather than by the bucket, so a gziped JSON file still expands in memory during a scan, while a snappy Parquet file is read natively in its compressed column chunks.

Creating External Tables

-- Create external table for CSV files
CREATE EXTERNAL TABLE `analytics.external_sales`
OPTIONS (
  format = 'CSV',
  uris = ['gs://my-data-lake/bronze/raw/sales/*.csv'],
  skip_leading_rows = 1,
  field_delimiter = ',',
  null_marker = '',
  ignore_unknown_values = true
);

-- Create external table for Parquet files
CREATE EXTERNAL TABLE `analytics.external_events`
OPTIONS (
  format = 'PARQUET',
  uris = ['gs://my-data-lake/bronze/raw/events/*.parquet']
);

-- Create external table for JSON files
CREATE EXTERNAL TABLE `analytics.external_logs`
OPTIONS (
  format = 'JSON',
  uris = ['gs://my-data-lake/bronze/raw/logs/*.json']
);

External Table Configuration

-- External table with partitioning
CREATE EXTERNAL TABLE `analytics.external_sales_partitioned`
PARTITION BY DATE(_PARTITIONTIME)
OPTIONS (
  format = 'PARQUET',
  uris = ['gs://my-data-lake/bronze/raw/sales/*']
);

-- Query external table with partition filter
SELECT *
FROM `analytics.external_sales_partitioned`
WHERE DATE(_PARTITIONTIME) = '2024-01-15';

-- Create table from external table
CREATE TABLE `analytics.sales`
AS
SELECT * FROM `analytics.external_sales`
WHERE amount > 0;

Authorized Views

An authorized view provides controlled access to data without granting direct table access, which is how a lake shares one copy with many audiences. The pattern matters because BigQuery permissions are checked against the view definition when the view is created rather than when it is queried: an analyst granted only roles/bigquery.dataViewer on the view reads the aggregated result and never sees the row level columns underneath, even though the view itself selects from a table they cannot open. That indirection is also the risk, since re-pointing a view at a different table silently changes what every consumer receives, so view changes belong in code review with the same weight as a schema migration.

Row level control needs a second mechanism. A view can filter on a column such as region, but the filter is then fixed for everyone who uses it, so multi-tenant isolation is usually built from a session parameter combined with a mapping table, or from BigQuery row access policies, which express the rule once on the table and apply it to every query path. Column level hiding of identifiers such as email is better handled with policy tags attached to the column, because the tag travels with the data into Looker, exports and applications instead of depending on each consumer remembering to omit the field.

Creating Authorized Views

-- Create authorized view
CREATE VIEW `analytics.sales_summary_view`
OPTIONS (
  description = 'Sales summary view for analysts',
  security = 'INVOKER'
)
AS
SELECT
  DATE(sale_date) as sale_date,
  region,
  product_category,
  COUNT(*) as transaction_count,
  SUM(amount) as total_amount
FROM `analytics.sales`
GROUP BY 1, 2, 3;

-- Grant access to the view
GRANT `roles/bigquery.dataViewer`
ON VIEW `analytics.sales_summary_view`
TO 'user:[email protected]';

-- Create dataset with authorized views
CREATE SCHEMA `analytics_views`
OPTIONS (
  description = 'Dataset for authorized views',
  access = [
    {'role': 'READER', 'specialGroup': 'projectReaders'},
    {'role': 'WRITER', 'specialGroup': 'projectWriters'},
    {'role': 'OWNER', 'specialGroup': 'projectOwners'}
  ]
);

View Security Patterns

python
# Security patterns for authorized views
security_patterns = {
    'row_level_security': """
        CREATE VIEW `analytics.filtered_view`
        AS
        SELECT * FROM `analytics.sales`
        WHERE region = 'US'
    """,
    'column_level_security': """
        CREATE VIEW `analytics.safe_view`
        AS
        SELECT
          sale_id,
          sale_date,
          region,
          amount
        FROM `analytics.sales`
        -- Exclude PII columns
    """,
    'aggregated_view': """
        CREATE VIEW `analytics.aggregated_view`
        AS
        SELECT
          DATE(sale_date) as sale_date,
          region,
          SUM(amount) as total_amount
        FROM `analytics.sales`
        GROUP BY 1, 2
    """
}

Data Ingestion Patterns

Ingestion sets the freshness a lake can promise, and the choice is driven by the source rather than by preference. Files arriving on a schedule are loaded with a scheduled Dataflow job or a BigQuery load job that matches the prefix convention; events with per second requirements go through Pub/Sub so that a burst is absorbed by retention rather than by a crashed writer; and databases are replicated with Datastream when the lake must mirror live tables. Whichever path runs, the objects written to bronze should carry an ingestion timestamp column that is distinct from the event timestamp, because the gap between the two is the metric that proves a pipeline is healthy rather than merely running.

Batch Ingestion

python
# Batch ingestion with Dataflow
import apache_beam as beam

def run_batch_ingestion():
    """Batch ingestion pipeline."""
    with beam.Pipeline() as pipeline:
        (
            pipeline
            | 'Read from Source' >> beam.io.ReadFromText('gs://source-bucket/*.csv')
            | 'Parse CSV' >> beam.Map(parse_csv)
            | 'Validate Data' >> beam.Filter(validate_record)
            | 'Write to Bronze' >> beam.io.WriteToText(
                'gs://my-data-lake/bronze/raw/sales/2024/01/15/',
                file_name_suffix='.parquet'
            )
        )

Streaming Ingestion

python
# Streaming ingestion with Pub/Sub and Dataflow
import apache_beam as beam
from apache_beam.transforms.window import FixedWindows

def run_streaming_ingestion():
    """Streaming ingestion pipeline."""
    with beam.Pipeline() as pipeline:
        (
            pipeline
            | 'Read from Pub/Sub' >> beam.io.ReadFromPubSub(topic='projects/my-project/topics/sales')
            | 'Window' >> beam.WindowInto(FixedWindows(60))
            | 'Write to Bronze' >> beam.io.WriteToText(
                'gs://my-data-lake/bronze/raw/sales/',
                file_name_suffix='.parquet'
            )
        )

Data Quality

Quality checks belong at the layer boundary, not in the report that eventually shows a wrong number. The cheap checks run on every load and block promotion: a primary key that must be unique, a required column that must be populated, a numeric range that must hold, and a freshness rule that fails when the newest row is older than the SLA. The expensive checks, such as distribution comparisons against the previous week or cross-table reconciliation against a source total, run on a schedule and raise a ticket instead of blocking, because they catch drift that no single row can reveal.

Data Validation

python
# Data quality validation
import pandas as pd
from great_expectations.core import ExpectationSuite, ExpectationConfiguration

def validate_data_quality(file_path):
    """Validate data quality."""
    df = pd.read_parquet(file_path)
    
    # Define expectations
    expectations = ExpectationSuite('sales_data')
    expectations.add_expectation(
        ExpectationConfiguration(
            expectation_type='expect_column_values_to_not_be_null',
            kwargs={'column': 'sale_id'}
        )
    )
    expectations.add_expectation(
        ExpectationConfiguration(
            expectation_type='expect_column_values_to_be_unique',
            kwargs={'column': 'sale_id'}
        )
    )
    expectations.add_expectation(
        ExpectationConfiguration(
            expectation_type='expect_column_values_to_be_between',
            kwargs={'column': 'amount', 'min_value': 0, 'max_value': 1000000}
        )
    )
    
    # Validate data
    result = df.validate(expectations)
    return result.success

Data Lineage

python
# Track data lineage
def track_lineage(source_path, destination_path, transformation_type):
    """Track data lineage."""
    lineage = {
        'source': source_path,
        'destination': destination_path,
        'transformation': transformation_type,
        'timestamp': datetime.now().isoformat(),
        'pipeline_id': 'pipeline_001'
    }
    
    # Store lineage metadata
    store_lineage_metadata(lineage)

Monitoring and Alerting

Four signals separate a maintained lake from a neglected one. Bucket size by prefix, charted over weeks, shows whether compaction and lifecycle rules are actually firing or whether small files are accumulating. The count of objects created per day against the count of bytes written reveals the small file problem before query latency does. Dataflow job failure and retry counts catch ingestion that is silently re-processing the same window, and a freshness metric computed from the newest event timestamp is the single number that tells an analyst whether to trust today's dashboard. Alert on freshness rather than on job success, because a pipeline can succeed while producing nothing.

Monitor Data Lake Metrics

python
# Monitor data lake metrics
from google.cloud import monitoring_v3
import time

def monitor_data_lake(project_id, bucket_name):
    """Monitor data lake metrics."""
    client = monitoring_v3.MetricServiceClient()
    project_name = f"projects/{project_id}"
    
    # Monitor bucket size
    interval = monitoring_v3.TimeInterval()
    interval.end_time = time.time()
    interval.start_time = time.time() - 3600
    
    results = client.list_time_series(
        request={
            'name': project_name,
            'filter': f'resource.label.bucket_name = "{bucket_name}" AND metric.type = "storage.googleapis.com/storage/total_bytes"',
            'interval': interval,
            'view': monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL
        }
    )
    
    for result in results:
        print(f'Bucket size: {result.points[0].value.int64_value / 1024 / 1024 / 1024:.2f} GB')

Best Practices

The seven habits below are ordered by how often skipping one turns into an incident. Layering and lifecycle rules prevent the two common failures, an unreplayable bronze layer and a bill that grows faster than the data. Versioning and authorized views cover the two dangerous humans, the one who deletes and the one who over-shares. Everything after that is refinement, but each item is cheap to apply at the start of a project and expensive to retrofit once terabytes and several teams are involved.

  1. Implement proper layering - Bronze, Silver, Gold architecture
  2. Use lifecycle rules - Optimize storage costs automatically
  3. Enable versioning - Protect against data loss
  4. Create external tables - Enable direct querying in BigQuery
  5. Use authorized views - Control data access securely
  6. Monitor data quality - Implement validation and alerting
  7. Track data lineage - Maintain data provenance information

Common Mistakes

Writing thousands of tiny objects straight into one prefix

Fix: Run compaction so files land in the hundred megabyte to one gigabyte range, and partition the path by date so listings stay small.

Applying an Archive transition at thirty days to data still queried weekly

Fix: Check the minimum storage duration and retrieval fee first; Archive requires 365 days and charges 5 cents per GB to read back.

Granting analysts read access on bronze instead of a curated view

Fix: Share an authorized view over gold so permissions apply to the definition, not to the underlying table.

Key Takeaways

  • Bronze keeps the raw payload so any interpretation can be rebuilt, which is the whole reason a lake exists next to a warehouse
  • Prefixes are the only index a bucket has: date hierarchies keep listings cheap and make lifecycle rules targetable
  • Storage class economics are set by minimum duration and retrieval fees as much as by the monthly rate, so Autoclass suits unpredictable bronze data
  • External tables cost nothing to store and everything to scan repeatedly, so promote a query pattern to a native table once it repeats

Interview Questions

Q1: When should data stay an external table and when should it be loaded?

Keep it external while the prefix is being explored or queried rarely, because there is no storage charge; load it into a native partitioned table once a query repeats, because repeated scans of external data cost more than the copy.

Q2: How does an authorized view restrict access differently from IAM on the table?

The view's definition is evaluated when it is created, so a user with permission only on the view reads the filtered or aggregated result and never gains access to the underlying columns.

Q3: What breaks if versioning is enabled without lifecycle rules?

Every overwrite and delete leaves a noncurrent version that keeps billing at its own storage rate, so the bucket grows monotonically until a rule deletes aged noncurrent versions.

Q4: Which metric tells you a lake is going stale before users complain?

Freshness computed from the newest event timestamp per prefix, alerted against the SLA, because job success only proves the pipeline ran and not that it produced current data.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert GCP Data Engineering Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement