Skip to content

Instantly share code, notes, and snippets.

@mohashari
mohashari / snippet-10.sql
Created March 14, 2026 15:12
Code snippets — Database Indexing Strategies
-- After creating the foreign key
ALTER TABLE orders ADD CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id);
-- Always add this index
CREATE INDEX idx_orders_user_id ON orders(user_id);
@mohashari
mohashari / snippet-2.go
Created March 14, 2026 15:12
Code snippets — Redis Caching Strategies
func UpdateUser(ctx context.Context, user *User) error {
// 1. Update database
if err := db.UpdateUser(ctx, user); err != nil {
return err
}
// 2. Update cache immediately
cacheKey := fmt.Sprintf("user:%s", user.ID)
data, _ := json.Marshal(user)
redis.Set(ctx, cacheKey, data, 15*time.Minute)
@mohashari
mohashari / snippet-2.go
Created March 14, 2026 15:12
Code snippets — Microservices Architecture Patterns
type OrderSaga struct{}
func (s *OrderSaga) Execute(orderID string) error {
steps := []SagaStep{
{Execute: paymentService.Charge, Compensate: paymentService.Refund},
{Execute: inventoryService.Reserve, Compensate: inventoryService.Release},
{Execute: shippingService.Schedule, Compensate: shippingService.Cancel},
}
var completed []SagaStep
@mohashari
mohashari / snippet-2.ini
Created March 14, 2026 15:12
Code snippets — Postgresql Performance Tuning
# checkpoint_completion_target: spread checkpoint writes
checkpoint_completion_target = 0.9
# wal_buffers: WAL write buffer (usually auto)
wal_buffers = 16MB
# synchronous_commit: set to off for async writes (risk: lose ~100ms of data on crash)
# Use only if you can tolerate this trade-off
synchronous_commit = off
@mohashari
mohashari / snippet-2.go
Created March 14, 2026 15:12
Code snippets — Message Queues Kafka Rabbitmq
// All events for user 42 go to the same partition
kafka.Message{
Key: []byte("user-42"), // Hashed to determine partition
Value: eventData,
}
@mohashari
mohashari / snippet-2.go
Created March 14, 2026 15:12
Code snippets — Grpc Vs Rest
func (s *server) Chat(stream pb.ChatService_ChatServer) error {
for {
msg, err := stream.Recv()
if err == io.EOF {
return nil
}
// Broadcast to other users...
stream.Send(&pb.ChatMessage{Content: "echoed: " + msg.Content})
}
}
@mohashari
mohashari / snippet-2.go
Created March 14, 2026 15:12
Code snippets — Jwt Authentication Deep Dive
func RefreshTokens(refreshToken string) (accessToken, newRefreshToken string, err error) {
// Validate refresh token against database
stored, err := db.GetRefreshToken(ctx, refreshToken)
if err != nil || stored.ExpiresAt.Before(time.Now()) {
return "", "", errors.New("invalid or expired refresh token")
}
// Generate new tokens
accessToken, _ = GenerateAccessToken(stored.UserID)
newRefreshToken = generateSecureRandom(32)
@mohashari
mohashari / snippet-2.yaml
Created March 14, 2026 15:12
Code snippets — Cicd Pipeline Github Actions
build:
name: Build & Push Docker Image
runs-on: ubuntu-latest
needs: test
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v4
- name: Set up Docker Buildx
@mohashari
mohashari / snippet-2.go
Created March 14, 2026 15:12
Code snippets — System Design Rate Limiting
func (rl *SlidingWindowLogLimiter) Allow(key string, userID string) bool {
now := time.Now().UnixMilli()
windowStart := now - rl.windowMs
pipe := redis.Pipeline()
// Remove old entries
pipe.ZRemRangeByScore(ctx, key, "0", strconv.FormatInt(windowStart, 10))
// Count current window
countCmd := pipe.ZCard(ctx, key)
// Add current request
@mohashari
mohashari / snippet-10.go
Created March 14, 2026 15:12
Code snippets — Go Programming Concurrency
// WRONG: panics if close is called twice
close(ch)
close(ch) // panic: close of closed channel
// RIGHT: use sync.Once
var once sync.Once
safeClose := func() { once.Do(func() { close(ch) }) }