This document establishes optimization principles based on successful patterns from our codebase, particularly the 87% code reduction achieved in the trial user upgrade flow optimization. These principles leverage extended thinking methodologies to ensure thorough analysis before implementation.
"The best code is no code. The second best code is code that already exists and works."
Leverage existing patterns
Extend before creating
Verify through reactivity
Eliminate duplication
Reduce complexity
Based on Anthropic's Extended Thinking methodology, always follow this decision tree:
graph TD
A[New Feature Request] --> B{Can existing code handle it?}
B -->|Yes| C[Extend existing code]
B -->|No| D{Can we modify existing patterns?}
D -->|Yes| E[Adapt and extend]
D -->|No| F{Is the new code reusable?}
F -->|Yes| G[Create abstraction]
F -->|No| H[Reconsider approach]
C --> I[Document extensions]
E --> I
G --> J[Create new pattern]
H --> A
Before writing any code, complete this extended thinking exercise:
## Existing Pattern Analysis
- [ ] What similar functionality already exists?
- [ ] Which queries/mutations handle related data?
- [ ] What UI components display similar information?
- [ ] Which hooks manage related state?
## Code Reuse Opportunities
- [ ] Can I extend an existing table instead of creating a new one?
- [ ] Can I add fields to an existing query return?
- [ ] Can I enhance an existing hook with new computed properties?
- [ ] Can I modify an existing component with conditional rendering?## Proposed Solution Complexity
- Lines of new code: ___
- New files created: ___
- New database tables: ___
- New API endpoints: ___
## Optimized Alternative
- Lines extending existing code: ___
- Files modified: ___
- Fields added to existing tables: ___
- Existing endpoints enhanced: ___
If optimized < 50% of proposed, proceed with optimization.// DON'T: Create separate tracking table
campaignTracking: defineTable({
userId: v.id('users'),
source: v.string(),
medium: v.string(),
// ... 10 more fields
})
// Requires joins, separate queries, sync logic// DO: Add fields to users table
users: defineTable({
// ... existing fields ...
// Campaign tracking (minimal additions)
campaignSource: v.optional(v.string()),
inviteCodeUsed: v.optional(v.string()),
})
// Data locality, no joins, existing indexes work// DON'T: Create similar queries
export const getTrialUsers = query({ /* ... */ })
export const getActiveTrials = query({ /* ... */ })
export const getExpiringTrials = query({ /* ... */ })// DO: Add to getUserStatus
export const getUserStatus = query({
handler: async (ctx) => {
// ... existing logic ...
return {
// ... existing fields ...
// Just add what's needed
isTrialFromCampaign: Boolean(user?.campaignSource),
trialDaysRemaining: calculateDaysRemaining(user),
}
}
})// DON'T: Create overlapping hooks
export function useTrialStatus() { /* ... */ }
export function useCampaignData() { /* ... */ }
export function useUserMetrics() { /* ... */ }// DO: Extend useSubscription
export function useSubscription() {
const userStatus = useQuery(api.users.getUserStatus)
// Add computed properties for new features
const enhancedData = useMemo(() => ({
...userStatus,
// New campaign-aware properties
shouldShowTrialOffer: userStatus?.isTrialing && userStatus?.daysRemaining <= 3,
campaignEffectiveness: calculateCampaignROI(userStatus),
}), [userStatus])
return enhancedData
}// ❌ DON'T: Manual state synchronization
const [userData, setUserData] = useState()
const [trialData, setTrialData] = useState()
useEffect(() => {
// Polling or manual updates
}, [])
// ✅ DO: Let Convex handle reactivity
const userStatus = useQuery(api.users.getUserStatus)
// Automatically updates everywhere when data changes// Public API (client-accessible)
export const getUserData = query({
handler: async (ctx) => {
// Return only what client needs
}
})
// Internal operations (server-only)
export const updateSensitiveData = internalMutation({
handler: async (ctx, args) => {
// Secure operations
}
})// ❌ DON'T: Create redundant indexes
.index('by_campaign', ['campaignSource'])
.index('by_trial_status', ['subscriptionStatus'])
.index('by_campaign_and_status', ['campaignSource', 'subscriptionStatus'])
// ✅ DO: Reuse existing indexes with filters
const trials = await ctx.db
.query('users')
.withIndex('by_subscription_status', q => q.eq('subscriptionStatus', 'trialing'))
.filter(q => q.neq(q.field('campaignSource'), undefined))
.collect()Use this scoring system (inspired by Extended Thinking with Tool Use):
| Criteria | Extend Existing | Create New |
|---|---|---|
| Similar data structure exists | +3 points | -3 points |
| Can reuse existing indexes | +2 points | -2 points |
| Existing queries return related data | +3 points | -3 points |
| UI components show similar info | +2 points | -2 points |
| Would require <50 lines to extend | +3 points | -3 points |
| Would introduce circular dependencies | -5 points | +5 points |
| Significantly different domain | -3 points | +3 points |
Score > 5: Extend existing code
Score < -5: Create new implementation
Score -5 to 5: Deeper analysis required
Inspired by Extended Thinking Tips:
Pass 1: Discovery (No Code)
- Find all related existing code
- Document current patterns
- Identify extension points
Pass 2: Design (Minimal Code)
- Write interface changes only
- Update type definitions
- Plan data flow
Pass 3: Implementation (Optimized Code)
- Implement with maximum reuse
- Add only essential new logic
- Document why choices were made
// Instead of new component
export function SubscriptionStatus() {
const { userStatus, campaignData } = useSubscription()
return (
<>
{/* Existing UI */}
{/* Conditionally show new features */}
{campaignData?.isTrialFromCampaign && (
<CampaignBadge source={campaignData.source} />
)}
</>
)
}// Instead of new queries
export const getUserStatus = query({
handler: async (ctx) => {
const user = await getUser(ctx)
// Compute new properties from existing data
return {
...user,
// Derived campaign metrics
campaignConversionValue: user.subscriptionTier
? prices[user.subscriptionTier] * 12
: 0,
isHighValueTrial: user.subscriptionTier === 'creator' && user.isTrialing,
}
}
})// 4 new tables
// 10+ new queries
// 5+ new components
// Complex state management
// Manual sync logic// Extended 2 existing tables (+11 fields)
// Extended 1 query (getUserStatus)
// Extended 1 hook (useSubscription)
// Leveraged Convex reactivity
// No sync logic neededResult: 87% code reduction, better performance, easier maintenance
// ❌ Multiple queries
const user = useQuery(api.users.getUser)
const subscription = useQuery(api.subscriptions.getSubscription)
const usage = useQuery(api.usage.getUsage)
// ✅ Single query returning all data
const userStatus = useQuery(api.users.getUserStatus)
// Returns user + subscription + usage in one call// Use existing indexes with filters instead of new indexes
.withIndex('by_subscription_status', q => q.eq('subscriptionStatus', 'trialing'))
.filter(q => q.neq(q.field('campaignSource'), undefined))// ❌ Sequential operations
for (const item of items) {
await ctx.db.patch(item._id, updates)
}
// ✅ Batch when possible
const promises = items.map(item =>
ctx.db.patch(item._id, updates)
)
await Promise.all(promises)Each new table adds:
- Schema complexity
- Join requirements
- Sync challenges
- Migration overhead
Ask: Can this data live in an existing table?
Before creating getUserTrialStatus when getUserStatus exists:
- Can getUserStatus return trial fields?
- Can we add a
includeTrialparameter? - Can computed properties derive what we need?
Never create database structure to match UI components. Instead:
- Store data in its most logical form
- Use queries to transform for UI
- Let components compute display values
When extending existing code:
// Document WHY you're extending
export const getUserStatus = query({
handler: async (ctx) => {
// ... existing implementation ...
// OPTIMIZATION: Added campaign fields here instead of creating
// separate campaignTracking table. Saves joins and maintains
// data locality. See: trial-optimization-2025-07-01
return {
// ... existing fields ...
campaignSource: user?.campaignSource,
inviteCodeUsed: user?.inviteCodeUsed,
}
}
})Track optimization success:
| Metric | Target |
|---|---|
| Code reduction vs initial approach | >50% |
| Reused existing patterns | >70% |
| New files created | <3 per feature |
| New database tables | 0 (extend existing) |
| Query complexity | No new indexes |
| Implementation time | <50% of estimate |
Before submitting optimized code:
- Extended existing tables instead of creating new ones
- Reused existing queries with additions
- Leveraged existing hooks and components
- No duplicate state management logic
- Documented why extensions were chosen
- Maintained backward compatibility
- Added fields are optional (v.optional)
- No circular dependencies introduced
- Performance same or better
- Code reduction >50%
- Extended Thinking Documentation
- Extended Thinking Tips
- Convex Best Practices
- Trial Optimization Case Study
Remember: Every line of code is a liability. The best feature is one that requires no new code, just better use of what exists.