토큰 소비에 영향을 주는 요소
1.
요소: Dimension 수
영향: 많을수록 비쌈
예시: content_id 1개 vs 9개(metadata)
2.
요소: Metric 수
영향: 많을수록 비쌈
예시: 2개 vs 5개
3.
요소: 날짜 범위
영향: 길수록 비쌈
예시: 7일 vs 30일 vs 60일
4.
요소: Dimension 카디널리티
영향: 고유값 많으면 비쌈
예시: content_id, page_path 등
5.
요소: 반환 row 수
영향: 많을수록 비쌈
예시: -
6.
요소: 필터 복잡도
영향: 복잡할수록 비쌈
예시: -
결론
Dimension, Metrics를 필요한 부분만 가져오는 쿼리가 필요함. In List Filter를 쓰는 방식으로 최대한 배치당 데이터를 줄이고 배치 용량을 늘려서, 시간을 나누어 가져오면 토큰 절약이 가능함.
GA4 Quota check code
"""
GA4 Quota 확인 스크립트 (로컬 전용)
.env 파일 또는 프로덕션 SSM에서 SA 키를 가져와 GA4 API 쿼터를 조회합니다.
Usage:
python local-workers/scripts/check_ga4_quota.py
"""
import os
import base64
import json
import warnings
from dotenv import load_dotenv
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import RunReportRequest, DateRange, Metric
from google.oauth2 import service_account
from google.auth.crypt import _python_rsa
warnings.filterwarnings('ignore', message='.*malformed keyfile.*')
ENV_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
SSM_PROPERTY_ID_KEY = '/GA/GCP_PROPERTY_ID'
SSM_SA_KEY = '/GA/GCP_SA_KEY'
def get_credentials():
""".env에서 AWS 인증 + SSM에서 GA 인증 정보 로드"""
load_dotenv(ENV_PATH)
import boto3
ssm = boto3.client('ssm', region_name=os.getenv('AWS_DEFAULT_REGION', 'ap-northeast-2'))
response = ssm.get_parameters(
Names=[SSM_PROPERTY_ID_KEY, SSM_SA_KEY],
WithDecryption=True
)
params = {p['Name']: p['Value'] for p in response['Parameters']}
return params[SSM_PROPERTY_ID_KEY], params[SSM_SA_KEY]
def create_ga_client(sa_key_b64, property_id):
sa_info = json.loads(base64.b64decode(sa_key_b64))
# SA 키의 exponent 이슈로 python RSA signer 사용
signer = _python_rsa.RSASigner.from_service_account_info(sa_info)
credentials = service_account.Credentials(
signer=signer,
service_account_email=sa_info['client_email'],
token_uri=sa_info['token_uri'],
scopes=['https://www.googleapis.com/auth/analytics.readonly']
)
return BetaAnalyticsDataClient(credentials=credentials), property_id
def check_quota(client, property_id):
request = RunReportRequest(
property=f'properties/{property_id}',
date_ranges=[DateRange(start_date='yesterday', end_date='today')],
metrics=[Metric(name='screenPageViews')],
return_property_quota=True
)
response = client.run_report(request)
return response.property_quota
def main():
print('.env 로드 → SSM에서 GA 인증 정보 가져오는 중...')
property_id, sa_key_b64 = get_credentials()
print(f'Property ID: {property_id}')
print('GA4 API 쿼터 조회 중...\n')
client, pid = create_ga_client(sa_key_b64, property_id)
quota = check_quota(client, pid)
# consumed = 이번 요청이 소비한 토큰 (누적 아님)
# remaining = 해당 기간에 남은 토큰
print('=== GA4 Quota 현황 ===')
if quota.tokens_per_day:
r = quota.tokens_per_day.remaining
print(f'토큰(일간): 남음={r:,} (이번 요청 소비={quota.tokens_per_day.consumed})')
if quota.tokens_per_hour:
r = quota.tokens_per_hour.remaining
print(f'토큰(시간): 남음={r:,} (이번 요청 소비={quota.tokens_per_hour.consumed})')
if quota.concurrent_requests:
print(f'동시요청: 활성={quota.concurrent_requests.consumed}, 남음={quota.concurrent_requests.remaining}')
if quota.server_errors_per_project_per_hour:
print(f'서버에러: 사용={quota.server_errors_per_project_per_hour.consumed}, 남음={quota.server_errors_per_project_per_hour.remaining}')
print()
if __name__ == '__main__':
main()
Python
복사


.avif&blockId=31054939-a7ac-80a9-863c-fea284e55781&width=32)
