Cost optimization কৌশল
এই পাঠে যা শিখবেন
- Cloud warehouse-এ bill কোথায় খরচ হয় — anatomy of a $50K/month invoice
- BigQuery slot ও Snowflake credit — কীভাবে কম খরচে একই কাজ
- Partition + cluster + materialized view — তিন বড় lever
- FinOps culture — Bangladesh startup-এ runway বাড়ানোর কৌশল
১ · Cost কোথা থেকে আসে — anatomy of a bill
ভাবুন একটি Bangladesh-based fintech — Pathao Pay. তারা BigQueryBigQueryGoogle Cloud-এর serverless data warehouse. বিল হয় storage + processed data (per TB scanned) ভিত্তিতে। Slot reservation মডেলেও available.-এ চলে। মাসিক bill — ৩৮,০০০ USD. CFO প্রশ্ন করেন — "এত কেন?" Engineering team breakdown করে দেখায়:
- Compute (query) — ২৬,০০০ USD (৬৮%) — প্রতিদিন প্রায় ১,২০০ TB scan. বেশিরভাগই dashboard auto-refresh ও poorly-written ad-hoc.
- Storage — ৭,৫০০ USD (২০%) — ১৫০ TB hot storage, ৬৪০ TB cold. Old log table যা কেউ দেখেও না।
- Streaming insert — ২,৫০০ USD (৬%) — Kafka → BigQuery direct, batch হলে ৭৫% সস্তা হত।
- Egress (cross-region/internet) — ২,০০০ USD (৬%) — Tableau Bangladesh-এ self-hosted, BigQuery US-এ — ক্রস-region transfer.
এই বিশ্লেষণ থেকে — কোথায় optimization-এ সর্বোচ্চ ROI তা স্পষ্ট। শুধু compute optimize করলেই অর্ধেক bill কাটা যায়।
১) Visibility: "কে কতটা পোড়াচ্ছে?" — query attribution, team-wise dashboard.
২) Right-sizing: "compute ক্ষমতা actual usage-এর সাথে match করছে কি?"
৩) Smart storage: "hot data hot-এ, cold data cold-এ।"
৪) Query efficiency: "একই answer কম scan-এ।"
২ · BigQuery cost model — bytes scanned
BigQuery-এর on-demand pricing — প্রতি TB scanned $৬.২৫ (২০২৫)। এর মানে:
$$\text{Cost per query (USD)} = \frac{\text{bytes scanned}}{2^{40}} \times 6.25$$
একটি ১০ TB table-এ SELECT * একবার = ৬২.৫ USD. ১০০ analyst দিনে ১০ বার চালালে = ৬২,৫০০ USD/দিন। বছরে ২৩ million USD শুধু একটি বদ-অভ্যাসে।
কীভাবে কম scan:
- Partition pruning:
PARTITION BY date+WHERE date = '2025-05-01'→ শুধু সেই দিনের bytes scan. - Clustering:
CLUSTER BY user_id→ user-filter query-তে কাছাকাছি bytes একসাথে। - Column selection:
SELECT *ভুলে যান। শুধু লাগবে এমন column. - LIMIT trick: BigQuery-তে
LIMITscan কমায় না — full table scan আগে। Sample চাইলেTABLESAMPLE. - Approximate aggregations:
APPROX_COUNT_DISTINCTexact-এর চেয়ে ১০০x সস্তা।
৩ · Snowflake — credit ও warehouse sizing
Snowflake-এ bill credit-ভিত্তিক — আপনার warehouse (compute cluster) কত সেকেন্ড চলেছে। T-shirt size — XS, S, M, L, XL, 2XL... 6XL. প্রতি step double — XS ১ credit/hour, S ২, M ৪, L ৮।
মূল সিদ্ধান্ত:
- Auto-suspend: default ১০ মিনিট। আমাদের অভিজ্ঞতায় ৬০ সেকেন্ড optimal — কেউ query করলে ৩ সেকেন্ড restart.
- Auto-resume: ON রাখুন। Off রাখলে query fail.
- Multi-cluster: Spike traffic-এ একই warehouse-এর অনেক cluster auto-spawn. ১ থেকে ১০।
- Sizing rule: ছোট থেকে শুরু (XS/S). যদি queue depth বাড়ে — bigger বা multi-cluster. বড় warehouse-এ small query চালালে — পয়সা পুড়ে।
Workload separation:
WH_LOAD— ETL job (Medium, 24/7).WH_BI— dashboard (Small, auto-suspend 1 min).WH_ADHOC— analyst ad-hoc (XS, strict timeout).WH_DS— Data scientist heavy queries (Large, manual approve).
৪ · Storage tiers — সবচেয়ে সহজ win
AWS S3-এ ৭টি tier:
- S3 Standard — $0.023/GB/month — hot, frequently accessed.
- Intelligent-Tiering — auto-move based on access pattern. Default choice.
- Standard-IA — $0.0125/GB — masik 1-2x access.
- One Zone-IA — $0.01/GB — re-creatable data.
- Glacier Instant — $0.004/GB — কম access, মিলিসেকেন্ড retrieval.
- Glacier Flexible — $0.0036/GB — মিনিট থেকে ঘণ্টা retrieval.
- Glacier Deep Archive — $0.00099/GB — ১২+ ঘণ্টা retrieval, ৭ বছর+ retention.
Lifecycle policy: "৩০ দিনের পর Standard-IA, ৯০ দিনের পর Glacier" — সম্পূর্ণ automated. ১ TB log-এ ১২ মাসে — Standard-এ $২৭৬, Deep Archive-এ $১২। ৯৬% সাশ্রয়।
৫ · Materialized view ও result cache
Materialized view: একটি query-র result physical-এ store, এবং automatically refresh. ১০০ analyst একই dashboard query চালালে — ১ বার compute, ১০০ বার lookup.
-- প্রতি ঘণ্টায় auto-refresh
CREATE MATERIALIZED VIEW analytics.daily_revenue_mv
PARTITION BY date_day
CLUSTER BY country
AS
SELECT
DATE(placed_at) AS date_day,
country,
COUNT(*) AS orders,
SUM(amount_bdt) AS gmv_bdt
FROM `daraz-bd.raw.orders`
WHERE placed_at >= '2024-01-01'
GROUP BY 1, 2;
-- query এই MV-তে hit করবে automatic, original table নয়
SELECT date_day, gmv_bdt
FROM `daraz-bd.raw.orders`
WHERE country = 'BD'
AND DATE(placed_at) BETWEEN '2025-04-01' AND '2025-04-30';
Result cache: BigQuery ও Snowflake দুটোই — অপরিবর্তিত query ২৪ ঘণ্টা cache করে। Repeat চালালে free. Cache-hit rate dashboard-এ check করুন।
৬ · Partitioning ও clustering — practical guide
Partition rule of thumb:
- Time-series data → date column-এ partition (DAY বা MONTH).
- Geographic data → region column.
- Avoid: high-cardinality column (user_id) — too many small partitions.
- Daraz orders table —
PARTITION BY DATE(placed_at)+CLUSTER BY (country, customer_segment).
৭ · FinOps culture — visibility ছাড়া optimization অসম্ভব
FinOpsFinOps (Financial Operations)Cloud খরচ ব্যবস্থাপনার একটি cross-functional discipline — engineering, finance ও business একসাথে কাজ করে real-time খরচ visibility ও accountability তৈরি করতে। framework-এর ৩ phase:
- Inform: "কে কত খরচ করছে?" Dashboard প্রতি team-এ। Slack alert "$X exceeded budget".
- Optimize: "কীভাবে কম?" — উপরের সব technique.
- Operate: automation — auto-shutdown weekend dev warehouse, cost-aware CI/CD checks.
-- প্রতি team-এর ১৫ দিনের spend
SELECT
COALESCE(labels.value, 'unlabeled') AS team,
ROUND(SUM(total_bytes_billed) / POW(1024, 4), 2) AS tb_billed,
ROUND(SUM(total_bytes_billed) / POW(1024, 4) * 6.25, 2) AS usd_cost,
COUNT(*) AS query_count
FROM `region-asia-south1`.INFORMATION_SCHEMA.JOBS_BY_PROJECT
LEFT JOIN UNNEST(labels) AS labels
ON labels.key = 'team'
WHERE creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 15 DAY)
AND job_type = 'QUERY'
AND state = 'DONE'
GROUP BY team
ORDER BY usd_cost DESC;
--@@SET LABEL team:risk) থাকলে — এই query-তে team-wise cost. বড় শাস্তি না, transparency কাজ করে। "ohh আমার team-এর ৪২% bill?" — তখন optimize অভ্যাস তৈরি হয়।
৮ · Bangladesh startup-এ cost-conscious patterns
বাংলাদেশের একটি startup-এ মাসিক $৫,০০০ cloud bill — সেটা একজন senior engineer-এর salary-র সমান। তাই FinOps survival.
- Reserved instance/commitment: Predictable workload-এ ৩-বছরের commit — ৫০-৭০% discount. Snowflake ও AWS দু'টোতেই।
- Spot instances: Spark batch job-এ — ৭০% সস্তা, কিন্তু evict-able. Resilient pipeline-এ চমৎকার।
- Open-source self-hosted: ছোট scale-এ Postgres + Metabase — Snowflake-এর চেয়ে ১০x সস্তা। ২০ TB-এর পর scale-এ flip.
- Local data center hybrid: Bangladesh-এ পক্ষে Robi/Beximco-এর data center-এ co-locate. Cold archive cheap.
- Egress avoidance: Daraz cross-region না করে — single region-এ rest + compute. Egress bill nuisance.
- Aggressive sampling: A/B test analysis-এ ১০০% data নয় — ১% sample-এ ৯৯% answer.
SELECT * আনলিমিটেড চালায়। ২ সপ্তাহ পর CFO-র কাছে surprise bill. Solution — onboarding-এ cost training, slot-reservation hard-cap, query-level cost-estimate UI.
৯ · Sample cost dashboard — yaml configuration
# প্রতি team-এর hard cap
resource_monitors:
- name: WH_BI_MONITOR
credit_quota: 1000 # masik 1000 credits = ~$2,500
frequency: MONTHLY
notify_at_percentages: [50, 75, 90]
actions:
- threshold: 100
action: SUSPEND # 100%-এ warehouse off
- threshold: 110
action: SUSPEND_IMMEDIATE # running query-ও kill
- name: WH_DS_MONITOR
credit_quota: 500
frequency: WEEKLY
actions:
- threshold: 90
action: NOTIFY # শুধু slack alert
ভাবনার প্রশ্ন
প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।
প্র ০১ আপনার Snowflake bill একদিনে $২০০ থেকে $২,০০০ — ১০x jump. কোথা থেকে শুরু করবেন investigation? কী কী সম্ভব cause?
এটি একটি real "war room" scenario — প্রতিটি data team-এর শুরুতে অন্তত একবার ঘটে। Investigation systematic হতে হবে, panic-driven নয়।
Step 1 — Time slice:
SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORY— কোন warehouse spike?- Hourly granularity-তে — exact কখন শুরু? Midnight cron? Business hour?
- একটি warehouse না multiple? Scope বুঝুন।
Step 2 — Query attribution:
QUERY_HISTORY-তে — top ১০ expensive query সেই window-তে।- User, role, query_text dump. প্রায়ই — একজন analyst, একটি broken query, infinite loop.
সম্ভাব্য causes — frequency order:
- (১) Cartesian explosion: JOIN-এ key miss → ১০ million × ১০ million row. সবচেয়ে common. 10x bill instant.
- (২) Auto-suspend disabled: কেউ accidentally
ALTER WAREHOUSE SUSPEND_RESUME = FALSE. Idle-ও running. - (৩) Warehouse upsize: কেউ "performance issue" debug করতে XS → XL বানিয়ে ভুলে গেছে।
- (৪) Multi-cluster spike: max_clusters ১০ — concurrent dashboard load-এ সব ১০ spawned.
- (৫) Data growth: নতুন large table loaded — clone/CTAS-এ underlying scan ৪০ TB.
- (৬) ML training: data scientist Snowpark-এ heavy iteration.
- (৭) Schedule miss: Airflow DAG cron mistake — hourly হয়ে গেছে minutely.
- (৮) Replication storm: failover/replication lag → bulk re-replicate.
Immediate mitigation:
- Suspect warehouse-এ
ALTER WAREHOUSE SUSPEND— bleeding stop. - Resource monitor temporary attach — strict cap.
- Slack-এ team-কে notify, root cause finding-এ সবাই focused.
Post-mortem actions:
- Runaway query auto-kill policy — query timeout ৩০ মিনিট default.
- CI/CD-তে dbt run cost estimate — PR review-এ "this query will scan 12 TB" warning.
- Anomaly detection — Slack bot "yesterday spend = ১০x avg → check".
- Runbook documented — পরের বার বাচ্চাও follow করতে পারবে।
মূল কথা: Bill spike — engineering signal, finance crisis নয়। দ্রুত response, blameless post-mortem, automated guardrails — মূল remedy. প্রতিটি incident future incident-এর insurance.
প্র ০২ BigQuery on-demand বনাম slot reservation — কোনটা কখন? Bangladesh-এ ছোট startup-এর কী choose করা উচিত?
এই decision অনেক CFO ও CTO-কে রাত জাগিয়েছে। ভুল হলে — হয় bill predictable নয়, নয়তো over-provision.
On-demand pricing:
- $৬.২৫/TB scanned, পেমেন্ট প্রতি query.
- Pros: No commitment, idle-এ $0, spike-এ unlimited capacity, simple.
- Cons: Bill unpredictable, runaway query expensive, no cost ceiling default.
Slot reservation (Editions: Standard/Enterprise/Enterprise Plus):
- Slot = compute unit. ১০০ slots ≈ ১ medium warehouse.
- Commitment: Annual ৩৪% discount, 3-year ৫২% discount.
- Pros: Predictable bill, cost ceiling, autoscaling within reservation.
- Cons: Underutilized হলে wasted, peak load-এ queue.
Decision matrix — মাসিক spend ভিত্তিক:
- <$২,০০০/মাস: On-demand, simpler accounting.
- $২,০০০-$১০,০০০: Hybrid — baseline reservation + on-demand spillover.
- $১০,০০০+: Heavy reservation, ৩-year commitment for predictable workload.
- $৫০,০০০+: Edition + autoscaler — slot-based fully.
Bangladesh-এ ছোট startup (e.g., ১০-৫০ employee fintech):
- প্রথম ৬ মাস: on-demand. Pattern বোঝা যাবে।
- ৬-১২ মাস: pattern stable → annual reservation (baseline 30-40% covered).
- Sweet spot: reservation = avg daily slot usage × 0.7. বাকিটা on-demand burst.
- Quota alert + budget alert আগেই set.
Common pitfalls:
- "Reservation = always cheap" — ভুল। যদি ৪০% utilization, on-demand cheaper.
- "3-year commitment safe" — startup pivot করলে stuck.
- Forget mixing — flex slot (hourly) emergency spike-এ।
Snowflake-এর সাথে comparison:
- Snowflake পুরো credit-based — slot ও warehouse model একসাথে।
- Storage Snowflake অত্যন্ত সস্তা ($২৩/TB/মাস) BigQuery-র চেয়ে।
- Compute concurrency Snowflake-এ multi-cluster — BigQuery-তে slot-pool.
মূল কথা: Pricing একটি spectrum — startup-এ flexibility (on-demand), enterprise-এ predictability (commitment). Hybrid approach — সবচেয়ে real-world. Quarterly review — workload pattern বদলালে commitment-ও re-evaluate.
প্র ০৩ Materialized view-এর dark side কী? কখন এটা cost বাড়ায়, কমায় না?
MV "magic bullet" না। ভুলভাবে ব্যবহার করলে — bill কমার বদলে বাড়ে। অনেক junior engineer এই trap-এ পড়েন।
MV কখন anti-pattern:
- (১) Highly volatile base table: প্রতি সেকেন্ডে inserts. MV continuous refresh = compute storm. Update overhead actual benefit ছাড়িয়ে যায়।
- (২) Low query frequency: MV একবার read-এর জন্য বানানো — refresh cost > query saving. Rule: at least ১০-২০x read-write ratio.
- (৩) Storage cost ignored: MV একটি extra physical table. ১ TB raw → MV ০.৫ TB → effectively ১.৫ TB stored.
- (৪) Stale-data tolerance অভাব: Real-time analytics-এ ১ ঘণ্টা lag unacceptable হলে — MV-র async refresh fit না।
- (৫) Many similar MVs: ৫০ dashboard-এ ৫০টা MV — maintenance hell, schema drift risk.
BigQuery vs Snowflake MV-র subtle difference:
- BigQuery: smart query rewrite — original table query MV-তে redirect automatic.
- Snowflake: explicit reference to MV — query rewrite limited (Enterprise feature).
- BigQuery MV সব JOIN support করে না — limitations check.
- Snowflake-এ Dynamic Table — newer alternative, often better.
Better alternatives — কখন?
- Daily aggregate batch: dbt incremental model + scheduled run. Predictable, debuggable.
- BI extracts: Tableau extract, Power BI dataset — BI tool-এ caching.
- Application-level cache: Redis/Memcached — < 100ms response চাইলে।
- Pre-aggregation in stream: Flink/Spark Streaming → directly write summary table.
MV-এর correct use case:
- Dashboard-heavy queries — same query ১০০x দিনে।
- Stable base table — daily batch update.
- Aggregation + filter — significant compute reduction.
- "Hot path" SLA queries — millisecond response চাই।
মূল কথা: MV একটি compute-storage trade. Storage সস্তা, compute দামি — তাই সাধারণত win. কিন্তু "always create MV" mindset — reflective, not analytical. প্রতিটি MV-কে treat করুন একটি product feature: clear owner, refresh schedule, deprecation criteria.
প্র ০৪ একটি bKash-style fintech-এ — DAU ১০ million, transaction ৫ million/দিন। আপনি $100K/month cloud bill কে $40K-এ নামাতে চান। কী strategy?
Bangladesh-এর largest MFS-এ এমন কাজ — engineering লidership-এর top 3 priority. ৬০% reduction ambitious কিন্তু realistic — যদি systematically attack করেন।
Phase 1 — Visibility (week 1-2):
- Cost dashboard team-wise, query-wise — Cloud Cost Anomaly Detection enable.
- Top 50 expensive query identification — Pareto rule (২০% query = ৮০% cost).
- Idle resource audit — orphaned warehouse, unused MV, dormant table.
- Per-feature cost attribution — "loan disbursement pipeline = $৮K/মাস?"।
Phase 2 — Quick wins (week 3-6):
- Auto-suspend tighten — 10min → 60sec. Saving estimate: $৮-১২K.
- Top 50 query partition + cluster + select-column rewrite. Saving: $১৫-২০K.
- Storage tier audit — ৯০-day-old transaction → Glacier IR. Saving: $৩-৫K.
- Streaming insert batching — micro-batch 1min instead of real-time. Saving: $২-৩K.
- Result cache hit-rate optimization — query template normalization. Saving: $২-৩K.
Phase 3 — Architectural (month 2-3):
- Materialized views top 10 dashboard queries. Saving: $৫-৮K.
- Reserved capacity / committed-use discount — annual commitment. Saving: $১০-১৫K.
- Workload separation — ETL/BI/ad-hoc warehouse split. Better right-sizing.
- dbt incremental models replace full-refresh batch.
- ML feature store — duplicate computation eliminate.
Phase 4 — Cultural (month 3-6):
- FinOps team formal — engineering + finance + product 1 representative.
- Weekly cost review — top 10 spender + improvement plan.
- Engineer onboarding — cost training mandatory.
- Internal cost-back chargeback — each team budget.
- "Cost goal" engineering OKR — feature parity + cost reduction.
Bangladesh-specific tactics:
- Onshore data center evaluation — BB compliance + cost saving.
- Off-peak schedule heavy job — Bangladesh business low at midnight, cheap spot.
- ISP egress negotiation — bulk traffic Bangladesh-based provider সস্তা।
- Open-source tool migration — managed BigQuery → self-host Trino + Iceberg для some workload.
Realistic timeline:
- Month 1: $100K → $৭৫K (visibility + quick wins).
- Month 3: $৭৫K → $৫৫K (architecture + reservation).
- Month 6: $৫৫K → $৪০K (culture + sustained discipline).
- Year 1: maintained at $৪০-৪৫K — even with 50% data volume growth.
Risks:
- Over-optimization → engineer time spent saving $২K/মাস (ROI low).
- Performance regression — partition pruning ভুলে latency double.
- Compliance break — data accidentally moved cross-region.
- Reservation lock-in — pivot হলে cost stuck.
মূল কথা: Cost optimization একটি systematic discipline — silver bullet নেই। Quick wins early, architectural longer-term, cultural permanent. Bangladesh-এ cloud bill = engineer salary, runway extension, investor confidence — তাই এটি technical work-এর চেয়ে business-critical.
অনুশীলন
-
Cost calculation: একটি ৫ TB BigQuery table-এ — naive query
SELECT * FROM orders WHERE country='BD'. Date partition নেই। মাসে এই query ১,০০০ বার চলে। মাসিক cost কত?প্রতি query: ৫ TB scan × $৬.২৫ = $৩১.২৫।
মাসে: ১,০০০ × $৩১.২৫ = $৩১,২৫০।
Optimization:
PARTITION BY DATE(placed_at)+CLUSTER BY country. ৩০ দিন-এর query-তে scan হবে ~০.০৫ TB → query cost $০.৩১ → মাসে ~$৩১০। ৯৯% সাশ্রয়। -
Snowflake warehouse sizing: Daraz-এ একটি analytics dashboard team — ১০ analyst, business hour-এ active, weekend usage low. কী warehouse config recommend করবেন?
CREATE WAREHOUSE WH_BI_TEAM WITH WAREHOUSE_SIZE = 'SMALL' -- শুরু এ small AUTO_SUSPEND = 60 -- 1 min idle AUTO_RESUME = TRUE MIN_CLUSTER_COUNT = 1 MAX_CLUSTER_COUNT = 3 -- spike-এ scale-out SCALING_POLICY = 'STANDARD' INITIALLY_SUSPENDED = TRUE STATEMENT_TIMEOUT_IN_SECONDS = 1800; -- 30 min runaway protectionResource monitor weekly $৫০০ cap; weekend 90% threshold notify.
-
Storage tiering plan: ১০ TB transaction log table (BB compliance — ৭ বছর retain). কীভাবে storage tier করবেন?
Tiering plan:
- 0-30 days: Hot (S3 Standard / Snowflake active) — analyst frequently access.
- 30-90 days: Standard-IA — মাসে কয়েকবার access, ৪৫% সস্তা।
- 90 days - 1 year: Glacier Instant Retrieval — fast retrieve, ৭০% সস্তা।
- 1-7 years: Glacier Deep Archive — rare access, ৯৬% সস্তা।
- Lifecycle policy: S3 lifecycle config বা Snowflake stage tiering automatic.
- Estimate: ১০ TB-এ Standard $২৩০/মাস → tiered $৪০-৫০/মাস। Annual saving ~$২,৪০০।
- Compliance proof: immutable Object Lock, audit trail.
আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ
- পাঠ ২৮ · প্রজেক্ট: end-to-end ML pipeline পরবর্তী পাঠ Capstone — সব শেখা একসাথে। Production-grade pipeline.
- পাঠ ২৬ · Data governance ও lineage আগের পাঠ Lineage cost optimization-এ unused dataset খুঁজতে সাহায্য করে।
- পাঠ ২২ · Snowflake পরিচিতি এই পাঠের সাথে সম্পর্কিত Snowflake-এর warehouse mechanics — cost-mind-এ থেকে design.
- সব AI Courses দেখুন ABCL TECH Python, ML, DL, NLP, CV, GenAI, RL, MLOps — সব AI কোর্স একসাথে।