ablog

不器用で落着きのない技術者のメモ

パフォーマンス分析に DuckDB を使ってみる

CSV などに出力された性能分析を行う際によく EXCEL を使ったりするが、DuckDB が便利だと聞いてインストールしてみた。

  • インストール
curl https://install.duckdb.org | sh
  • ~/.zshrc に以下を追加
export PATH='~/.duckdb/cli/latest':$PATH
  • 起動する
source ~/.zshrc 
duckdb
  • SQL を実行する
D  select a.query, trunc(a.total_exec_time/1000/1000/60) exec_time,
      b.query_cpu_time,
      b.query_blocks_read,
      b.query_execution_time,
      b.query_cpu_usage_percent,
      b.query_temp_blocks_to_disk,
      b.segment_execution_time,
      b.cpu_skew,
      b.io_skew
  from read_csv('./STL_WLM_QUERY.csv',ignore_errors = true) a, 
      read_csv('./SVL_QUERY_METRICS_SUMMARY.csv',ignore_errors = true) b 
  where a.query =b.query 
      and a.queue_start_time > '2025-06-12' 
  order by a.total_exec_time desc limit 30;
  • SQL の実行結果を CSV で export する。
COPY (
      select a.query, a.xid, b.query_id, a.pid, a.starttime, a.endtime, a.querytxt
      from read_csv('./STL_QUERY.csv',ignore_errors = true) a, 
          read_csv('./SYS_QUERY_HISTORY_trunc.csv',ignore_errors = true) b
      where a.xid =b.transaction_id
          and a.starttime > '2025-06-12'
  ) TO 'QUERY_ID.csv' (HEADER, DELIMITER '|');
||< 


**参考
-[https://duckdb.org/why_duckdb:title]
-[https://duckdb.org/docs/stable/sql/introduction.html:title]
-[https://www.youtube.com/watch?v=bZOvAKGkzpQ:title]

Redshift で現在から x 時間前のタイムスタンプを取得する

  • 現在から1日前のタイムスタンプを取得する。
# select trunc(sysdate)-1;
?column?
2025-06-10
  • 現在から16時間前のタイムスタンプを取得する
# select dateadd(hour,-16, sysdate);
date_add
2025-06-10 14:52:09.714924

psql で FETCH_COUNT を使って OOM Killer に kill されないようにする

Linuxpsql の実行結果をファイルに出力する際、結果セットのサイズが大きいと OS の OOM Killer に kill されることがある。
FETCH_COUNT を指定すると FETCH_COUNT 単位でメモリにキャッシュするようになる。

FETCH_COUNT の指定方法

psql -v FETCH_COUNT=1000 -A -h rs-ra3-4xl-4n.********.us-east-1.redshift.amazonaws.com -p 5439 -d dev -U awsuser
  • プロンプトで指定する
\set FETCH_COUNT 1000

参考

結論:FETCH_COUNT=Nを設定する

psql -v FETCH_COUNT=1000 

この場合、1000行毎に出力する。

元のpsqlコマンドの実行例

この場合クエリ結果は一回メモリにキャッシュされる。
そのため超大な結果を全部を一回メモリに抱えるまでファイルに出力されない。

psql -v "select * from test_table as t where t.id <> 0" > output.txt
psqlコマンドで大きな結果を逐次出力する

FETCH_COUNT
この変数が0より大きな整数値に設定されている場合、SELECT問い合わせの結果は、指定した行数の集合として取り出され、表示されます。 デフォルトの動作では、表示する前にすべての結果が取り出されます。 したがって、結果セットの大きさに関係なくメモリの使用量が限定されます。 この機能を有効とする場合に100から1000までの値がよく使用されます。 この機能を使用する際には、既に一部の行が表示されている場合、問い合わせが失敗する可能性があることに注意してください。

https://www.postgresql.jp/docs/9.4/app-psql.html

Amazon Redshift で Elastic resize の完了を確認する方法

Amazon Redshift で Elastic resize した後、バックグラウンドでノードスライスにデータを再分配が完了するまではクエリの実行に時間がかかる可能性がある。

2. このオペレーションはクラスターのメタデータを移行します。クラスターは数分間使用できません。クエリの大部分は一時的に停止され、接続は開いた状態になります。ただし、一部のクエリは削除される可能性があります。この段階は短い。
3. セッション接続が回復し、クエリが再開します。
4. 伸縮自在なサイズ変更は、バックグラウンドでノードスライスにデータを再分配します。クラスターは読み取りと書き込み操作に利用できますが、一部のクエリは実行に時間がかかる可能性があります。
5. 操作が完了すると、Amazon Redshift はイベント通知を送信します。

クラスターのサイズ変更 - Amazon Redshift

Amazon Redshift では、クラスターのスライスからノードへのマッピングが変更されると、Elastic リサイズの実行時にスライスのシャッフルが発生します。Amazon Redshift はデータをスライス全体に均等に分散して並列処理するため、ノードを追加または削除するとスライスが再分散されます。この再分散では、新しいスライス間でデータが分散され、効率的なパフォーマンスが維持されます。Elastic リサイズの実行にかかる時間は、クラスターのサイズ、データ量、およびワークロードアクティビティによって異なります。

Amazon Redshift での Elastic リサイズに関するトラブルシューティング | AWS re:Post

リサイズが完了すると、以下の AWS CLI コマンドを実行結果で Status が "SUCCEEDED" になる(リサイズ中は "IN_PROGRESS")。

aws redshift describe-resize --cluster-identifier mycluster
Amazon Redshift category Event ID Event severity Description
Monitoring REDSHIFT-EVENT-3537 INFO Cluster '[cluster name]' data transfer completed at [time in UTC].
Amazon Redshift プロビジョニングされたクラスターのイベント通知 - Amazon Redshift

実行例

  • Elasitc resize でクラスターのノード数を変更する。
% aws redshift resize-cluster \
    --cluster-identifier redshift-cluster-poc-central \
    --cluster-type multi-node \
    --node-type ra3.4xlarge \
    --number-of-nodes 4 \
    --no-classic
  • リサイズの状態を確認する
% while true
do
date -Iseconds
aws redshift describe-resize --cluster-identifier redshift-cluster-poc-central
sleep 30s
done

2025-06-11T05:27:37+09:00
{
    "TargetNodeType": "ra3.4xlarge",
    "TargetNumberOfNodes": 4,
    "TargetClusterType": "multi-node",
    "Status": "IN_PROGRESS", <-- 変更中は "IN_PROGRESS" になる
    "ResizeType": "ElasticResize",
    "TargetEncryptionType": "NONE"
}

...

2025-06-11T05:34:59+09:00
{
    "TargetNodeType": "ra3.4xlarge",
    "TargetNumberOfNodes": 4,
    "TargetClusterType": "multi-node",
    "Status": "SUCCEEDED",  <-- 完了すると "SUCCEEDED" になる
    "ResizeType": "ElasticResize",
    "Message": "Elastic resize completed successfully.",
    "TargetEncryptionType": "NONE"
}   
  • マネジメントコンソール([Amazon Redshift] - [Event])のイベントには完了すると REDSHIFT-EVENT-3537 が出力される。

  • STV_UNDERREPPED_BLOCKS
export PGPASSWORD="hoge"
while
true
do
date -Iseconds
aws redshift describe-resize --cluster-identifier redshift-cluster-trailing
psql -h alter-add-column-lab.********.ap-northeast-1.redshift.amazonaws.com -p 5439 -d dev -U awsuser -c "SELECT COUNT(1) FROM STV_UNDERREPPED_BLOCKS;"
sleep 10s
done

 -- count が 0 になれば OK
 count 
---------
 0

Amazon Redshift の ra3 インスタンスのローカルSSDのキャッシュについて

Amazon Redshift の ra3 インスタンスのローカルSSDのキャッシュについて


Compute nodes use large, high performance SSDs as local caches. Redshift leverages workload patterns and techniques such as automatic fine-grained data eviction and intelligent data prefetching, to deliver the perfor-mance of local SSD while scaling storage automatically to Amazon S3.

Figure 5 shows the key components of RMS extending from in-memory caches to committed data on Amazon S3. Snapshots of data on Amazon S3 act as logical restore points for the customer. Redshift supports both the restore of a complete cluster, as well as of specific tables, from any available restore point. Amazon S3 is also the data conduit and source of truth for data sharing and machine learning. RMS accelerates data accesses from S3 by using a prefetching scheme that pulls data blocks into memory and caches them to local SSDs. RMS tunes cache replacement to keep the relevant blocks locally available by tracking accesses to every block. This information is also used to help customers decide if scaling up their cluster would be beneficial. RMS makes in-place cluster resizing a pure metadata operation since compute nodes are practically stateless and always have access to the data blocks in RMS. RMS is metadata bound and easy to scale since data can be ingested directly into Amazon S3. The tiered nature of RMS where SSDs act as cache makes swapping out of hardware convenient.
RMS-supported Redshift RA3 instances provide up to 16PBs of capacity today. The in-memory disk-cache size can be dynamically changed for balancing performance and memory needs of queries.

Amazon Redshift re-invented - Amazon Science

Redshift の CW メトリクスの Write Latency

Write latency – Shows the average amount of time in milliseconds taken for disk write I/O operations. You can evaluate the time for the write acknowledgment to return. When latency is high, it means that the sender spends more time idle (not sending any new packets), which reduces how fast throughput grows.

Viewing cluster performance data - Amazon Redshift

Amazon Redshift でノード・スライスごとのブロック数を確認する

Amazon Redshift でノード・スライスごとのブロック数を確認する。

select b.node, a.slice, sum(blocknum)
from svv_diskusage a, stv_slices b
where a.slice = b.slice
group by b.node, a.slice
order by b.node, a.slice, sum(blocknum) desc;

node|slice|sum
0|0|2821012504
0|1|2885748816
0|2|2830922313
0|3|2967025944
1|4|5211643368
1|5|2820034230
1|6|2844777960
1|7|2769496495
2|8|2811089919
2|9|2843159619
2|10|2835198368
2|11|2783326269
3|12|2799212712
3|13|2765290236
3|14|2870821537
3|15|2874467798
(16 rows)