About Me

My photo
An experienced Data Professional with experience in Data Science and Data Engineering interested in the intersection of Machine Learning and Engineering.

Most Recent Post

2026-02-20

AB Testing != Feature Flagging

AB Testing != Feature Flagging

I hear this a lot. They seem the same, both flip experiences for users, both need a system to allow for this and some counts and analytics.

But essentially they different goals, even if teams can use the same codebase and infrastructure to implement and maintain these systems, they need to be considered differently. There is a different interface and thought process between turning one on, monitoring, and evaluating success.

The basics,

Websites will turn on different experiences for different groups of uses in order to

  • measure customer experience
  • evaluate internal systems 

Essentially to ask "Is this new setup better than what we had before?" 

Requirements

Let's start here with one system at a time, and then investigate any overlapping requirements.

The actual requirement is as simple as "is this change better?, should it always be used?"

Feature Flags

Feature Flags are internally focused. Their requirements are from engineering teams, for engineering teams, implemented by engineering team, and run by engineering teams and typically focus on 3 use cases,

  • Does this change make the infrastructure better?
  • Does this change meet the requirements asked for?
  • If this breaks, can we rapidly turn it off?

I don't think I've ever seen a feature flag that doesn't fit within these cases.

Latency & Scaling

If we change the underlying infrastructure like this, does it seems the same but cheaper, faster, or more robust?

Such as

  • Can we handle the same traffic at the same speed with 1 less node?
  • If we reorganize the JavaScript libraries, will loading be faster, with similar functionality?
  • Will Regionalized deploys work as expected?

Often individual users are not split here, but % of traffic to specific end points may be. So a single user may experience different infrastructure over a session or day, with the goal being that they don't notice the changes.

Most changes here are Engineers looking for large swings in specific metrics, with no change to other metrics. Systems work similarly all the time, so a high quality decision can be made quickly.

QA / Gradual Rollout

  • Can we rollout features all the way to production, and let QA/Stakeholders test at their leisure?
  • And
  • Can we rollout new features to a subset of users?

Teams will often use Feature Flags as a form of restricting who sees an experience in order to move fast with implementation, and allow other teams to move at a different pace, as well as gradually rolling out changes to ensure that systems, including human systems such as customer support, scale properly.

In this case, specific users or groups of users must be tracked to be allowed to see the changes.

Rapid Turn Off

This is used in situations where an experience or vendor breaking is known to incredibly impact a system or user experience. Often this can be turned off for a poor experience, but not catastrophically so.

For example, a payment processor may be experiencing stability issues. It's bad to not be able to accept payment, but worse if the payment hangs and user don't know if their order has gone through or not. Having a switch allowing the payment to be turned off can be a useful stop-gap while a more permanent solution is found.

AB Testing

AB Testing is typically focused externally, but can be turned internally as well. These tests come from a stakeholder trying to move some business metric. Since these metrics are usually highly dependent on who uses the system and what their intent is, they need statistical measurement to evaluate whether changes help or hurt a metric.

Groups of users are given different experiences in a highly controlled and tracked manner to allow for 

  • Statistical Design and Analysis
  • Allowing for High Quality Decisions

 Sophisticated AB Testing is extremely concerned with

  • Who sees the new experience?
    • Very specific groups will often be targeted.
  • When did they seen the new experience?
    • Data from before they see the change is treated different from after.

Teams will tune experiences to specific groups of users in order to increase metrics reliably and systematically. Without high confidence in the underlying system, stakeholders will be forced to make low quality decisions.

Feature Flagging compared to AB Testing

Commonalities here are

  • Specifics users see specific experiences and are locked into the experience

And differences are

  • % of traffic is sometimes acceptable for Feature Flagging, but never for AB Testing
  • Feature Flagging doesn't typically care about types of users seeing an experience, but AB Testing often does
  • Feature Flagging is looking for unchanged metrics or metrics with huge, obvious swings. Whereas AB Testing is teasing out 1% and 2% changes tuning an experience for the better.

Why does this conversation come up so much?

The underlying system and code is often the same for the two systems. Vendors exist and will sell both together, and programmers will often toggle between these experiences with identical lines of code.

The difference primarily exists in the instigation and analysis which are both outside of standard engineering responsibilities. So Engineering teams will view these systems as the same, and although they are not wrong, this difference can introduce subtle bugs, and a lack of confidence in AB Testing.

Alright then, what do we do?

Set expectations. Stakeholders and analysts can use consistent vocabulary and templates for documentation and ticketing. This communicates the differences to Engineering teams.

Engineering teams can solicit help from analysts on analyzing feature flags. Engineers can also be stakeholders eking out 1% and 2% changes via AB testing.

This is entirely a problem of

  • Communication
  • Documentation
  • Team Cohesion

If you have a single system that runs both, communicate and discuss this with stakeholders, analysts and engineers at every opportunity. Make sure everyone understands this one system may have different names and goals, but serves all equitably.

Conclusion

If you mean AB test, say AB test. If you mean Feature Flag, say Feature Flag.

Set goals beforehand, set expectations before a change, and communicate what success looks like early and often.

These are clearly different, with different goals, even if the underlying code is the same.


2025-12-05

A Primer on Eventing and Domain Events

A Primer on Eventing and Domain Events

Generally speaking an event is a record of something happening. Software will record something to a log and that's the event. They must be

  • Write only
  • With a Timestamp
  • An event type
  • Metadata related to the specific type 

Events can be used in two ways

  1. Real time systems
  2. Back end analysis

Events present a particular difficulty in that an events can interact and override each other. Such as for an ecommerce site, an order may come in as an event, but then an order cancel event may also come and together there is no order. 

But there was an order. For a period of time this order existed in the system, between the time between order made and order cancelled. 

Systems that process events in real time need to be able to handle these types of cases, and back end systems that run a reporting should include the order during the time the order existed.

So why do I as a software engineer or data professional care about events and how do I start to deal with this type of dataset?

What is an Event?

An event is simply a record of something happening. This may be something a user did, the system did, or more trivially some logging if database access, security events, or exceptions.

Typically they are stored and transmitted in a variety of methods including

  • Ad hoc storage to Database Tables
  • Logging to flat files or Log aggregation systems
  • Sent to a queuing system such as Kafka

Examples

Some typical examples are

Order was Placed - What items were ordered, when and by which customer.

Database was queried - A log that may be captured and used by an engineer to debug a production system.

Product Recommendations successfully re-generated and available for real time use.

Domain Events?

Domain Events are more specific they are geared towards significant and important events within a system that can be used to understand the main goals and calculate key KPIs.

For example, a user placing an order would absolutely be a domain event, but querying a database would not be a domain event. These are very specific to the team responsible for implementing and tracking these events and although some things like orders are likely to be applicable from company to company, every company is going to set these up differently.

As a side note, domain thinking by itself can help a company break their system up into manageable pieces where each is responsible for a single domain.

Domain events come into play because a domain must send data out for other teams to use, and teams don't care about "querying a database", but absolutely care about "a user placing an order". This approach to eventing allows emitting of events so that other systems can listen proactively to necessary events without having to also sort through a bunch of unrelated data.

Web Engineering

One of the biggest impacts to using domain events widely is that web teams can implement their underlying databases however they want to.

A common pattern with reporting at web companies is that the web engineering team transmits in the entire database downstream for use in analytics and reporting. I've seen this mechanism in a few ways, but the problem is that if the web team want to make a simple change - add a column, or rename a table, or split a table, they have to negotiate with downstream uses of that table.

Events help get away from this anti-pattern by enabling downstream users to rely on contractually obligated events being emitted. These events are separate from the database, allowing an application team to optimize their queries and table structures without having to negotiate with other teams.

This could be both an opportunity and a bit daunting to implement.

For the example above with orders a web team may start to implement a domain event when an order occurs and then find out that orders occur in multiple places across the system. On the one hand it can be hard to implement the domain event but on the other hand, large complex systems can be cleaned up and unified in such a way that the entire domain or "orders"is more easily understood and easier to maintain.

Data Engineering

Data engineering or analytics engineering teams often benefit greatly from eventing because it helps them to fulfill their obligations to both reporting and data science teams.

One of the core requirements on a data engineering team is to know the state of the system at any given point in time for the past few years. This becomes exceptionally complex when the source of your data is operational databases that have updates applied. What did the table look like yesterday? You have to know what the table looked like yesterday, and if it has updates, then teams will often need to store the entire table from yesterday.

This resents an enormous cost either in development time to clean this up or in storage costs to store multiple copies of databases.

Events are a solution to this. A streaming set of things happening in the system can just be stored in their raw form. Since there are no updates, there's no worry of storing duplicate data, nor is there a huge complexity in cleaning up the data set for use in reporting or machine learning. 

Data Science

A core part of building an understandable ML model is to know what was the state of the system into the past. Eventing is one methodology of allowing data science teams to both have high quality data sets where the state of the system is known for every point in time, and to allow the ML models to operate on streaming data.

Does your LLM need to know the customer's most recent order? Just store, and use when it's necessary. Does your model need to know how many times a user has refunded an order in the last month, just a trivial count.

This allows data science teams to build models that are low in leakage because they are able to understand exactly what data came in exactly when.

This does increase the complexity on building features for an ML model. Many times I've had conversations with people over what exactly is your training set, no, really what exactly is the training set? Data over the last 6 months is the not the same as data for all users from the last 6 months who have relevant data. Building models off of streaming data means teams have to think very carefully up front about features in order to ensure that they're fulfilling the requirements of the model and aligning with it's future implementation.

These types of eventing systems present both an opportunity to build high quality models for data science teams but also a Less straightforward method of building feature sets.

Data Analytics

A common problem on reporting teams is when data changes upstream. Web team renames a column and suddenly the entire reporting suite is broken. Analytics teams traditionally struggle with being held accountable for changes that are outside of their purview.

If you are an analyst, how many time in the last month has one of your reports broken due to upstream changes?

Events help them with this because The very nature of eventing forces teams to think deeply about what data is being produced and what reporting needs. Analytics gets a seat at that table to define events, instead of just being a downstream user of the data they are the stakeholder.

Conclusion

I barely mentioned Kafka. Often Kafka and eventing and domain events are conflated, but they're really different and Kafka is just one system that could be used for moving events. Eventing is a way of thinking about data flows and a methodology of scaling a engineering organization to many independent, encapsulated teams.

At your company, ask yourself, 

  • Have we built systems that are flexible and enable teams to work independently and at scale?
  • Can we build systems to allow advanced machine learning use cases to run robustly and at scale?
  • If we think of all our dependencies, how can we enable those teams and projects to work independently and at scale?

There is a funny bit here, these types of systems are old and companies still struggle to even understand whether or not they want to adopt them. I tried to illustrate the justification for that as opposed to the mechanism that a lot of books and blog posts focus on.

2025-06-26

Types Of Logs

Types Of Logs

Start with "what's a log"? Let's take the definition from here

  an append-only, totally-ordered sequence of records ordered by time.

I would add to this definition as

an append-only, totally-ordered sequence of records ordered by time generated by engineering systems

Engineering systems, our systems supporting websites, games, jets produce data that is required for many use cases across a company including

  • Machine Learning
  • Reporting
  • Debugging 

The above definition differs from a lot of other data sets used in websites in that it's "append only". The word "log" and "logging" gets many definitions and conversations can easily get muddled.  My attempt here is to tease out the differences between different types of logs to have more clear communication. I hope at the end to not have anything called a "log" as that would apply to all the below categories.

I propose that there are 3 categories of logs

Log CategoryTypical StakeholderFieldsExample
MetricsEngineeringName, Timestamp, ValueEndpoint Latency
ErrorsEngineeringTimestamp, textException in code
EventsData folksName, Timestamp, <custom values>New account creation

Metrics

 Metrics are a series of records that follow a typical pattern,

  • Name
  • Timestamp
  • Value

Standard examples are 

  • API latency
  • Count of failures

Development teams often monitor the behavior of a system for uptime and to decide where changes need to be made.

Is the system working well? Look at the plot of errors over time.

Which endpoint is slow? Look at the latency of all endpoints and see which one has the highest value.

Metric logging is an essential part of understanding the real time behavior of a system. 

Errors

If a piece of software hits an exception and throws an error the error and stacktrace are needed to fix the error.

Oftentimes software systems have a variety of logging levels such as DEBUG, INFO and ERROR. In practice in production there's generally none of these standard logs except for ERROR. This typically means an exception has occurred and should be corrected as soon as possible.

Sometimes metrics are calculated on top of errors but should be standalone and independent to increase both the speed, efficiency, and cost of the metrics being stored. Why calculate the metric off of thousands of strings when you just have the metric "12789" sitting there?

Error logging is an essential part of correcting fatal errors in a system. 

Events

Events are a record of what happened when and any associated data required to understand the full extent of this event.

Such as

  • New user created - userid, timestamp, user type
  • Recommendations are available for loading - in systems where product recommendations are produced in batch mode, this can be an efficient method of informing a production system to load new data in.

Event driven architectures are commonplace and typically powered by a queuing system such as Kafka which allows many listeners to pick and choose which events are required to power their specific service.

These systems are very powerful and uniquely suited to fulfill many data architectures such as 

  • Real time data science model execution
  • Reporting decoupled from production application databases 

These events are almost always needed perpetuity for data science teams to build new models as well as for reporting to understand systems and metrics.

As with many new AI/LLM powered architectures, Event Logging can also be used to track what actually happened, what input caused what output using which LLM. This can greatly aid in the understanding of AI systems making many thousands of decisions.

Conclusion

Append only data sets are commonly used across websites and are often called "logs" or "logging" when in reality development teams are generally talking about Metrics, Errors or Events.

Each type of log has it's own unique use cases and stakeholder and should be considered as an essential building block production systems. 

Being able to breakdown the type of record being asked for into the type of log that is required makes understanding and implementation much more straightforward and can be generalized as well.

2025-03-25

Filter on the Last Step

Filter on the Last Step

So you've written a bunch of code to build a data set for a model or report. Your code has joins and filters, and it's complex. Maybe hundreds of lines or maybe just lots of intricate joints and CTEs.
 
That's fabulous. Stakeholders are happy. Your code is done. You're happy. Everybody's happy.
 
And then you get a question "How many users in Georgia are filtered out?" or "Why is this particular customer filtered out?"
 
These become hard questions to answer because there's a series of steps and each step makes a decision. It's hard to reason how all the final filters are interacting together without having them all in a final dataset.

Prefer adding columns instead of filtering on the fly. Do the filtering at the end together in a way that allows for investigations of the interactions between filters.
| customer_id | col1 | col2 | filter_col1 | filter_col2 |
|-------------|------|------|-------------|-------------|
| 11          | ...  | ...  | 10          | California  |
| 22          | ...  | ...  | 11          | Georgia     |
| 33          | ...  | ...  | 113         | Washington  |
| 44          | ...  | ...  | 134         | California  |
| 55          | ...  | ...  | 12          | California  |
Below I'll walk through a couple different examples and reason through this been a bit more detail.

How does this work?

  1. Build your data site as normal - joins, CTE's, etc
  2. Instead of adding filters, add a column
    1. Instead of WHERE col1 > 10
    2. Add a column "col1". You can then have all the filter logic together at the end.
  3. Instead of a inner joint, doing an outer join
  4. Be sure to keep track of names as the additional columns can cause confusion
  5. Then at the end you've got your full day set.
    1. You can play with it, look at it do analytics on it store it, etc.
  6. Then to pull the final data set
    1. Filter as appropriate
    2. Add a distinct
    3. and you're done ✅

Filter As you Go

Suppose you have 2 datasets and you want to build a new dataset that removes customers who

  • Are not in California or Washington
  • Have not made an order in the last month

Customer Information "customers"

| customer_id | state      |
|-------------|------------|
| 11          | Washington |
| 22          | California |
| 33          | New York   |
| 44          | California |
| 55          | New York   |

Order Information "orders"

| customer_id | order_id | days_since_order |
|-------------|----------|------------------|
| 11          | 4444     | 10               |
| 11          | 4445     | 200              |
| 22          | 4449     | 11               |
| 33          | 4441     | 10               |
| 44          | 4440     | 200              |
| 44          | 4439     | 10               |

A Single Query would work fine

SELECT DISTINCT customer_id
FROM customers
JOIN orders ON customer_id
WHERE state IN ("California", "Washington")
AND days_since_order <= 30

So what happens now?

You've built your data set. You're done right? Well, until the questions start coming in,
  • Why did customer 44 get filtered?
  • How many orders were filtered?

These become difficult to answer because you've just run the query. Easy enough with this toy example to just run a couple different queries, but as SQL statements can become longer and more complex, it can become harder to determine the answers to these questions.

Filter Last

Instead build a full dataset like this

| customer_id | order_id | days_since_order | state      |
|-------------|----------|------------------|------------|
| 11          | 4444     | 10               | Washington |
| 11          | 4445     | 200              | Washington |
| 22          | 4449     | 11               | California |
| 33          | 4441     | 10               | New York   |
| 44          | 4440     | 200              | California |
| 44          | 4439     | 10               | California |
| 55          | 4433     | 250              | New York   |

Then filter like this,

SELECT DISTINCT customer_id
FROM full_dataset
WHERE state IN ("California", "Washington")
AND days_since_order <= 30

Now the questions are easy to answer

  • Why did customer 44 get filtered?
    • SELECT * FROM full_dataset WHERE customer_id == 44
  • How many orders were filtered?
    • SELECT COUNT(DISTINCT order_id)
      FROM full_dataset
      WHERE state NOT IN ("California", "Washington")
      AND days_since_order > 30

Performance Considerations

If I'm building a large data set, is that going to suck up resources on the database? Is it going to make the queries slower? Is it going to make a production run of this data set slower if I run this often?

This comes back to the core item - do you need to answer questions and investigate the dataset you have built? This is almost always yes, so then the question is whether you can optimize the compute required to do these investigations.
 
Options are generally
  • Make a view with the unfiltered dataset that can be used for investigations
  • Cache the unfiltered data and run investigations on this dataset
 It's a trade-off between compute for storage.

Conclusion

Filtering as you go has the benefit of thinking through the process as you're going through it. It feels quick. It feels easy. It feels like the way we were taught to do it in school in our early jobs.
 
Filtering later has the benefit of being able to reason about the data set and ask questions of the full unfiltered data without having to write a whole bunch of custom code. You have the final, unfiltered data set. You can ask questions on it and builds plots, charts, reports, anything needed to support the final project.

2024-10-31

On Data Flows for Machine Learning Services

On Data Flows for Machine Learning Services

Building data flows for Machine Learning systems is the mundane plumbing that ensures that a system is

  • transparent and testable
  • behaves as expected
  • has clear ownership
  • is scalable to high volume
  • is scalable to many ML services

A system is typically setup that will some id (typically a user id) and return some results such as a churn score or a set of recommendations. This is often an Rest or gRPC API call into a separate service running next to a website or web apps. The core of a system of this sort is a machine learning model that takes some data in and calculates some features and then returns a result.

Generally something like,

This is pretty straightforward, the core problem then is Where Does the Machine Learning Model get it's Features from?

  1. The application - ⚠️ Anti-pattern ⚠️
  2. Some other system
  3. The application as raw data - 💫 Best Practice 💫

It's so easy to think of machine learning as just a thing that works and provides these amazing insights and personalization, but without having the data sets in sync and set up properly, the actual experience of developing, debugging, monitoring, and extending can stall out or require excessive maintenance.

Data Flows

In order to check all these boxes,
  • transparent and testable
  • behaves as expected
  • has clear ownership
  • is scalable to high volume
  • is scalable to many ML services

A system must

  • Be usable in a non-production environment
  • Return production quality results in a non-production environment
  • Have clear boundaries which team is responsible for what part of the system
  • Scale to hundreds, thousands and millions of users
  • Scale to 2, 3, 60, 500 machine learning services

Features come from the application - ⚠️ Anti-pattern ⚠️

In this system, the application will make a call to the machine learning system, and it'll give it everything it needs with the call to generate a result.

Pros & Cons

A system of this sort is very easy to develop and deploy, but hard to maintain.

  • ✅ Be usable in a non-production environment
  • ✅ Return production quality results in a non-production environment
  • 🚫 Have clear boundaries which team is responsible for what part of the system
  • ✅ Scale to hundreds, thousands and millions of users
  • 🚫 Scale to 2, 3, 60, 500 machine learning services

The team developing the features is not typically the same team as is developing the machine learning model so there can be misunderstandings and bugs. There can also be limitations in the features to be developed. Machine learning models often take large amounts of data over time and applications don't always have this so readily available.

This type of system tightly couples the machine learning system to the application, as well as denies the ability for the data used to calculate the features to be genetically available to other machine, learning models.

Features come from some other system

 

In this system, the application will make a call to the machine learning system, and it will just give some user id that requires a result for.

Pros & Cons

A system of this sort is very easy to develop, deploy and maintain but hard to test.
  • 🚫 Be usable in a non-production environment
  • 🚫 Return production quality results in a non-production environment
  • ✅ Have clear boundaries which team is responsible for what part of the system
  • ✅ Scale to hundreds, thousands and millions of users
  • ✅ Scale to 2, 3, 60, 500 machine learning services

These types of systems are also fairly easy to set up often as batch mode systems that calculate the features separately from the application.

This is a really good place for teams to start if your team or organization has never spun up a machine learning model. It's very understandable, easy to roll out to, but requires more thinking on the testing side.

The main con here is the application and the machine learning responses are not in sync. So a user id in one system may not be useful in another system. This makes testing difficult in non-production environments as either the application will have a user id that will match to a different machine learning result, or the application will have a user id that will match to no result.

Features come from the application as raw data - 💫 Best Practice 💫

 

In this system, the application will send raw data into an aggregator (typically called a feature store), this data will then be made available to the machine learning model for use in calculating a score or recommendations.

Pros & Cons 

A system of this sort is very hard to develop and deploy, but easy to test and scale.
  • ✅ Be usable in a non-production environment
  • ✅ Return production quality results in a non-production environment
  • ✅ Have clear boundaries which team is responsible for what part of the system
  • ✅ Scale to hundreds, thousands and millions of users
  • ✅ Scale to 2, 3, 60, 500 machine learning services

This is the most robust pattern available to an organization. It allows for multiple models to leverage the same set of features, as well as separates out the concerns of who maintains the features and how they are calculated from who uses the machine learning result.

This type of system also allows for testing in non-production environments since all the data comes directly from an application.

This type of system should not be the first machine learning system an organization spins up. It takes a bit more sophistication, a bit more raw data being flowing out of the system and a whole other set of aggregations separate from the application owned by another team.
 
An organization should definitely spin up a system like this if it anticipates a few dozen machine learning systems to be spun up, or it has tight requirements on robustness, speed or quality.

Bonus: ⚠️ Anti-pattern ⚠️ Features come from both the application and another system 🪢

 


In this system, the application will make a call to the machine learning system, and it'll give it some of the data it needs with the call to generate a result, with other data coming from some other system.

Pros & Cons

A system of this sort is very hard to develop and deploy, and test and maintain.
  • 🚫 Be usable in a non-production environment
  • 🚫 Return production quality results in a non-production environment
  • 🚫 Have clear boundaries which team is responsible for what part of the system
  • ✅ Scale to hundreds, thousands and millions of users
  • 🚫 Scale to 2, 3, 60, 500 machine learning services

🤪 This type of system design is excellent if you'd like to tie yourself in and not stay up all night and be very unsure if your system is performing as you expected to 🤪

There are no pros to a system of this sort.

This system not only has issues with separation of concern, data being mismatched, but also has the fun added bonus of another method of data being mismatched. Not only may the user ids be mismatched but the features may be as well leading to a situation where instead of recommending books, the system may be recommending books, movies, tables and gibberish.

Notes on input datasets

There are just so many different ways to build a machine learning algorithm that the above examples are wrapped around "user id" being the input to the system. Really it could be any identification as a single field or multiple, simple or complex. The state matters here as much as the entity being evaluated.

For example it could "user id + book" indicating the model should generate recommendations for this user limited to "books".

Conclusion

Overall, it's best practice if the people and teams that own in the machine learning model also own the construction of the features that power of the model. Systems can be set up in such a way to support this goal or to detract from it.

Goal should be a generic system that powers not one machine learning model, but dozens, allowing for an organization to scale.

 

2024-09-25

Documentation for Data Systems

Documentation for Data Systems

How do I as a data professional communicate with my colleagues, my peers, myself in six months, and with the person we are going to hire next year?

How do I leave something behind for my colleagues to learn and access the thoughts that I had when I built something investigated something learned something or understood something?

I write this from the perspective of a data professional, but I really think this is pretty broadly applicable to most companies where people have to ask other people questions to learn information to get their job done. So really a lot of companies probably 🤪

Basically I think this boils down to 4 super related things that are needed to write and contribute documentation to your company and your colleagues.
  1. Accessible & Findable - Make sure it's open to the team that needs it, and that they can find it
  2. Incomplete & Living - Make sure you spent the appropriate amount of time and not a second more, but also that others' can extend and pick up where you left off

Accessible & Findable

Make sure it's open to the team that needs it, and that they can find it

In order for documentation to be used, it has to be open and findable to the team needing it.

This may seem simple but many a time I have tried to open a document and found the permissions locked. Or looked for a document I knew existed, but been unable to find it and had to ask around.

The companies and teams that move the fastest have open access to the data and information they need to accomplish their mission.

Incomplete & Living

  • Don't write everything
  • Don't try to capture everything
  • Don't try to solve every problem
  • Don't try to store every detail
  • Don't try to tell everybody everything
  • But also
    • Don't think that communicating status and state is not your problem

Do write what you know right now, and/or is at your fingertips, and also be done and leave TODOs and open questions.

A company, a project is like a quantum state. You can't actually know what's happening at any given point in time even if you had all the information. And having all the information would alter the system to an unknowable state.

Just aim for 20 minutes, leave open questions, and make sure the doc is accessible and open for updates and permissions, and come back! next week! next year! tinker, and a line here and there and see where it grows to 🌱

Wrap it up

todo there is more to say on wrapping together Accessible, Findable, Incomplete and Living.

Conclusion

Spending 20 minutes writing a piece of documentation is usually going to be a waste of time 😧

but

when you hit you hit big. Write 10 docs that take you 3 hours, and one of those will save someone between a day and a week of time.

In conclusion ⤵️

2023-08-07

Data Stored an In Code Calculation

Data Stored as In Code Calculation

Websites store a lot of information within code calculations. At the simplest this might be a function like

def year_of(a_date):
    return a_date.split('-')[0]

Instead of storing the year separately from the date, we have to piece different data together to determine the year. In this case it's simple, but you could imagine a function that takes multiple pieces of data and makes some determination to return a single data point.

Software does this all the time.

  • A user logs into the system, is there account "in good standing?" is calculated on the fly from a variety of database inputs as some custom calculation.
  • "Do they need a password reset?" is calculated on the fly.
  • "What's the most recent order?" is calculated on the fly from an orders database.

This is great, it keeps the software running, and provides a high quality experience for the user. However, there are a few drawbacks that can be encountered.

  1. Reporting: When a business person needs to know "how many users need a password reset?"
  2. Efficiency: When calculating the value takes a lot of resources
  3. Accuracy: When multiple places in the code calculate the value differently
  4. Functionality: When the business wants to force a decision for some subset of users

The easiest way to fix all these is by storing these values in the code and keeping them up to date through some in-code or batch process.

Why would a data point need to move from an in code calculation into a database lookup?

Sorting data in code is often a default. From just a few simple values, a tremendous amount of data can be derived. There is a balance between a more complex system using more resources and a simpler system calculating everything on the fly.

⚖️ As with everything, middle ground between "storing everything" and "storing a bare minimum" is the best solution.

Reporting

Businesses change, new questions get asked and business folks will ask questions that can only be answered by executing the code on every user or by recreating the logic in some backend SQL system. Recreating the logic can work for some situations, but there are extreme cases where the decision is complex, information is unavailable to the backend system to make the decision or where reporting and actual are desired to be 100% the same.

Best to align with existing dashboard and reporting systems and to realize when a data point is too complex to calculate using duplicate logic in some reporting system.

Not everything needs to be reported on and new data points should really only be provided if the business really needs this data. When storing new data in code it's important to ask whether this data needs to be reported on.

Efficiency

Caching is a tried and true method within software engineering and realizing when a data point needs to be cached is beyond the scope of this document.

But it's good to take a step back when caching a new value and ask whether it would be helpful to have this data point in reporting and whether this data point is calculated in multiple locations in the code.

Accuracy

Oh no, there are too many places in the code calculating the value slightly differently 🔀. It's not always possible to clean the code to have all the values point to some new logic or library since differences need to be investigated before porting everything to a standard library.

If the clean, robust data was stored for all the users, it can be easier to update existing code to use this since the differences in calculation are easier to compare.

Plus, a junior developer might not re-implement effective_to if it's stored in the database. Putting data into a database is a method of communicating "this data is available" around a complex, large codebase in a way that is separate from building a standard library.

Getting one place to store a robust data point is easy, but rolling it out can be hard and require different strategies and coordination.

Functionality

Oftentimes a business will want to have some complex one-off logic to force something to happen on the website.

Perhaps it's some onboarding module that only pops up in the user's first session, or the business needs to reset passwords en-mass.

The code logic can be updated, but if the value is stored in the database, a simple query could change all the values en-mass and therefore change the user experience without a code deploy.

New Architecture

Moving from calculating some data on the fly to storing it and looking it up again can be quite challenging.

  • What if half the data is stored in the database, but not the other half?
  • How exactly do I populate the database while maintaining a production system?
  • How do I know if the data needs to be updated?

In these situations it's important to ask 2 questions,

  • How stale can the data be? 1 day? 1 second?
  • Under what situations does the data need to be updated?

Migration - Example - Do they need a password reset?

In the standard case where users are forced to update their passwords every 6 months, this data can be quite stale.

It's easy enough to store an effective_to date in a database and to update it nightly or weekly.

This can allow business folks to do reporting on this data with questions such as

  • How many users have passwords that currently need resetting?
  • How many users have passwords that need to be reset in the next month?

And to allow a single location for the production software to lookup whether the password needs resetting.

Migration - Complex Pattern

In general a complex system may need a series of steps

  1. Update to calculate the data on the fly, and to store to a database
  2. Run a one-off transformation to execute this code for all users to populate the database
  3. Run a periodic job to update this data for all users
    1. How often this job needs to run is dependent on how stale this data can be
      1. May need to be run
      2. nightly
      3. asynchronously based on some event
      4. Both nightly and asynchronously
  4. Update the on the fly calculation to pull from the database and compare to the in-code calculation
    1. This can be required in the case where small differences can have large effects
  5. Update to no longer do the calculation on the fly 

💡A simple system may be able to skip or combine these steps.

Conclusion

Storing data in code is a common, preferred case but often reaches some limit in

  • Reporting
  • Efficiency
  • Accuracy
  • Functionality

There are methods of moving a data point from an in-code calculation into a database, but they have to be carefully considered for functionality and staleness.

🚚 Companies do this all the time! It's part of maintaining and extending a system to meet new news of the business.

🌱It's so common you may wonder why I bothered to write this down at all 💫

2022-12-02

Two Types of Data Engineers

Two Types of Data Engineers

There are 2 types of data engineers, those that come from a data/sql/warehouse background and those that come from a software engineering background.

Both are necessary to keeping a modern data system running and to keep a company provided with the data they need when they need it.

What does a Data Engineer "do"?

From What are all these Data people doing anyway?

Raw data can be messy and/or inaccessible. Data Engineers are responsible for building pipelines to pull and archive the raw data and to systematically clean datasets for use in downstream reporting. Other teams have data needs with requirements around how often the data is refreshed and data engineers have the skills to fulfill those requests.

  • Make clean data accessible with requirements around
    • When
    • Where
    • How
  • Optimize data flows for
    • Speed to delivery
    • Cost to operate

 Example Projects

  • Data Warehousing
    • Usually the flagship project of Data Engineering teams. Store the data in an archival format such that reporting, analytics and modeling can run on top
  • Real Time Server Side User Profiles
    • Make user data accessible in real time for modeling, analytics or for display on a website

Two Types

There are two types of complimentary Data Engineers

  • Analytics Engineers
  • and
  • Software Data Engineers

Typically one is focused on Analytics problems and building clean, aggregated tables, while the other is focused on APIs and moving data from one location to another.

Both are essential to a well functioning Data Engineering team which will recognize the complimentary skill set required to pull and move data and to prepare data for analysis and reporting.

Analytics Engineers

Analytics Engineers love to clean datasets for generic use. As companies grow analysts will realize that their reporting dashboards are going slower and slower and are increasingly harder to maintain. This is often due to the dashboard querying raw data while joining dozens of tables and dealing with hundreds of corner cases.

Analytics Engineers are here to be the middle ground between "the business is asking for 16 things simultaneously" and "this query is running slow, perhaps a different sortkey would help". They build clean, aggregated datasets used to power dozens of different dashboards each with a different perspective on a dataset.

Typically Analytics Engineers work heavily in SQL systems and run nightly jobs that clean and aggregate incoming data into datasets that analysts can easily use. They are engineers and follow engineering principles but are business focused and listen carefully to analyst problems and needs. Part of being an Analytics Engineers is looking at bigger issues and finding places where 3 different problems could be solved by building a single, clean dataset.

Example projects

  • Clean Revenue data - dataset with 1 row per revenue event
    • Seems simple, but could easily involve joining 10+ datasets and accounting for that one time in 2018 when we had a 24 hour website bug that caused all collected revenue to be recorded in the raw data as 10x the actual revenue.
  • Clean Event data - dataset with 1 row per user action
    • Once again, seems simple and a "SELECT * FROM atable" seems like it would work, but always doesn't in practice.
    • Sometimes there are 10 duplicated events each with timestamp that differs by milliseconds.
    • Sometimes events are collected in 2 or 3 different locations and each have their own bugs and idiosyncrasies that need to be accounted for before joining into a single clean dataset.
    • Each corner case has to be accounted for and differs from company to company and project to project.

Software Data Engineers

It's all fine and good to build nice datasets for analytics use, but first you have to have data ready to go.

That's the job of the Software Data Engineer.

Sometimes you have a 3rd party vendor that has an API that returns a base64 encoded JSON string that has a bunch of encrypted keys with serialized results that needs yet another API call to decode 😧, No problem for a software data engineer. They will pull this data, massage it, throw out the obvious junk, check that it looks good and load it for use by analysts, data scientists, and of course, analytics engineers.

They also make data available for use by other teams via APIs. In some ways they seem to be backend engineers and sometimes there is overlap, but their focus is on data problems. Reporting, machine learning and other analytics systems are what they are most concerned with.

Example projects 

  • Copy production datasets for backend use
  • Pull data from 16 different vendors into a single system that can combine them all together
  • Work closely with Data Scientists to make model results available via APIs
    • There is an overlap here with Machine Learning Engineers who focus exclusively on this problem.

What's the difference between a Data Engineer and a Backend Engineer?

Often there isn't much difference. Backend engineers will run data transformations and batch jobs that clean data and make it accessible to front end website. Both of these specialties involves a lot of software engineering, API development and movement of clean datasets from one system to another.

The difference between these jobs tends to be who their primary stakeholders are. If they are primarily responsible to other engineers and product managers they tend to be lumped in as backend engineers. In this case they often run in sprints with other product engineers and their focus is on clean production datasets.

On the other hand if they are primarily responsible to data scientists and data analysts they they are typically lumped in with "data" engineers. These teams will often run separate from teams who are focused exclusively on user experience in websites and apps as their responsibilities are more around reporting and supporting machine learning models.

Conclusion

What exactly is the difference here? SQL, Python, Java are just programming languages, these folks are all Engineers, why are there 2 types?

I think is an historical accident. Data Base Administrators (DBA) were a job function for decades and still exist at larger companies. Their primary focus is building SQL systems that analysts can use to do reporting.

But then data science arose in the last 15 years and wanted to do more. They wanted more data, messier data and wanted to use it all to produce machine learning scores in a timely manner. So Software Data Engineers were created to support them.

This lead to a confluence of events where companies look at their data teams and say "we just need some analysts and engineers, right?" The lump Data Science and Data Analysis together as well as Analytics Engineering and Backend Engineering and get an awkward combination.

It's our job to tease apart these differences to build well rounded teams focused on whatever the business needs.


2022-08-06

Data Engineering Tips and Principles

Data Engineering Tips and Principles

Software Engineering patterns are pretty well established within the industry.

  • Develop locally and deploy to production
  • Lock down production data, systems and processes
  • Use unit tests, QA and integration tests to validate code changes
  • Do code reviews, design reviews and use appropriate standards for the technologies used

 Data folks are often different because

  • Sometimes there is just 1 database with the tables and columns, so development happens on this production system
  • SQL is commonly used which makes automated tests difficult to achieve
  • Real data is used to catch corner cases and validate transformations during development

A lot flows out of these points that makes Data Engineering a different discipline than Software Engineering. It becomes hard to lock down production data and systems and if SQL is the primary language used, then data engineering teams will sometimes not have any tests at all.

Below I've tried to outline a few points that can help bring more stringent development standards into Data Engineering while still maintaining the differences between Data and Software Engineering.

  • Develop with small data
  • Save tests for future use
  • Have a clear process to deploy something to production

These can help to bring more discipline to a scrappy data engineering team.

Development

The first step to developing a data transformation is to understand the real data. Understanding the real data can help to develop faster and to have reproducible tests.

Like a lot of folks, I've sat there and watched my SQL query run for 45 seconds, made a small change, and iterated, and iterated, and lost a day just watching my query run. Thinking about the final result and making an effort to understand the data beforehand can drastically speed up the development and well as create more robust and higher quality code.

I suggest the following approach,

  1. Understand the real data - Document it including common queries and corner cases
  2. Recreate a tiny dataset that covers the real data including corner cases
  3. Consider the output of your transformation on this tiny dataset.
  4. Develop your code with this tiny dataset until your code matches your expectations
  5. Run the code on the full dataset, and if there are failures or discrepancies then your original understanding of the dataset is incomplete, so return to step 1 and iterate.
This allows rapid development working with small data, while still having the emphasis on the real data.

Testing

Developers typically run tests on their transformations to see if they are correct. These tests should be stored with the final output and be re-usable. Typically Software Engineers use automated unit tests, but SQL can also be tested. Whether the tests are SQL statements, Python unit tests or a checklist, they are an artifact that allows code to be updated with confidence and should be maintained and used before deployment.

Generally software engineers have it right here. Run code locally (or in a container) and every manual test should be documented as an automated test.

This allows for a pyramid of dependencies to be created. Does the code compile? Do the tests pass? Are guidelines followed? If yes, then the code is ready for production.

Deployment

Deploying to production should be an isolated, reviewed and approved button click.

Standard Software Engineering code reviews should be used here to catch any obvious issues and to ensure code guidelines and standards are followed.

If deploying to production means manually changing 6 different configuration values, s3 buckets, database endpoints or table names, then a system should be devised to deploy to production via some automated process.

The automation can be built on to enforce standards. Folks breaking production because their tests don't pass? Update the automated deploy to disallow this.

Administration

Data Engineers often have to maintain a database with permissions, tables and views and other changes that can occur without an actual deploy. A view can be created through a SQL client without having to go through any process.

Some of these should have checklists and guidelines and some should required enhanced permissions. Need to update permissions so that a user can query a table? Go through the checklist and follow standards. Need to build a new schema? Talk to an administrator with access to a super user account. No need to recreate the wheel every time you need to add permissions, no need to allow engineer to do anything on the system.

Need to build a view? Great, follow the standards across the team for code storage, table location and permissions.

Most administration work is very routine and it's a waste of an engineer's time to start from scratch every time they are taking on this type of work.

Conclusion

A robust system is constructed step by step on 

  • A standard development method
  • Followed consistently
  • Updated when necessary
  • And agreed upon by the team

Generally with Engineers this means

  • Work on small data that is well understood
  • Track validation and tests as part of production code
  • Document standard methods and approaches so anyone can work on anything
  • Collaboratively review each others work

Don't lose sight that we are engineers building a structure step by step and the structure is only as strong as it's weakest point. Standards, Tests, Process, Reviews help keep the structure strong.

2022-05-13

Book Suggestions

Book Suggestions for Data Practitioners

This is a collection of books that I've either read or partially read that I think is valuable for people who work in Data.

These books are for a range of skill levels from beginners to advanced data folks.

A lot of these books receive continued updates, so be sure to get the newest version.

These 2 don't really fit in any other section, but are probably the most useful.

Data Visualizations

Engineering

Machine Learning

Statistics and Analytics




2022-04-01

Why does my startup need a Data Team anyway?

Why does my startup need a Data Team anyway?

This is a reasonable question. Any business should have a healthy skepticism to hiring. Trying to hire your way out of a problem is feasible, but can be a really expensive proposition for any company.

Typical questions,

  • Can't the engineers, the accountants and finance people handle data stuff?
  • What benefit do I get from hiring data analysts, data engineers and data scientists?

The engineers, accounts and finance folks can take a business a long way. They can make plots and charts and determine if the business is making money or going bankrupt. They can support quarterly reports to a board of directors.

A Data Team tackles more fast moving, predictive, larger and messier datasets than accounting and finance and free up the engineers to do actual engineering work. Having data specific folks is a specialization of skill and allows focus on a bounded domain.

Let's start with an Exercise

Let's calculate Revenue over last month from a table with columns

  • customer id
  • revenue
  • revenue date time

This is super easy right?

  • Filter by date time to the "last month"
  • Sum the revenue, and you're done!

In practice, the tables are never this simple. They tend to have dozens of columns and revenue data can be spread across another dozen tables. Trying to get a handle on 12 * 12 * number of records for even a small number of records takes some time and effort.

Typically a revenue calculation would involve,

  • refund amount
  • item sold
  • type of item sold
  • different revenue streams that may have their own tables
    • or might even be stored in the same table in different columns
  • etc, etc, more and more columns and tables, on and on and on

Accountants and finance folks can handle these type of problems in Excel with little difficulty. An engineer can run some SQL, hand the data off to accounting and they can load it into Excel. Excel is great, but does have has size limitations. There is only so much memory on a laptop and the business complexity will continue to increase.

More tables, more SQL joins, and more corner cases cause businesses to increase the amount of time required to support basic revenue calculations. At some point, it becomes a half time or full time position for a dedicated person.

Is there a data team?

Accounting and finance may gradually ramp up the work for the engineer to support their efforts. Does your business have an engineer spending more than 50% of their time supporting data pulls? Does it have 2 engineers spending 25% each?

Then your business already has a data team, it just hasn't been verbalized. That's not a great position to be in. Best to have clear communication, goals and expectations on folks.

I would propose that the equivalent of one-half on an engineer's time spent supporting data pulls for accounting and finance is a data team.

What do I mean by "Team"?

In the above example accounting and finance were the core of the data teams, but not all businesses have such a complex accounting or finance group. Some tech startups have more questions on the business operations than they do on their revenue and tax commitments.

  • How many people visited the website today?
  • Where did our new visitors come from?
  • How can we encourage them to stay?

This can lead a business into data analytics. Analysts focus on business questions and business use cases. But their focus is so oriented towards business problems, that they are necessarily the strongest engineers. In order to move faster and have more regularity in their delivered reports they will need support, and thus a business may hire a Data Engineer or Analyst Engineer.

This can cascade into a full data team with analysts, engineers and scientists - What are all these data people doing?

Data teams grow gradually, one person at a time until someone stands up and says "Look Over Here! We have a data team".

Conclusion

Maybe your organization doesn't need a full data team. A single accountant can support a large, complex business, and maybe that's enough.

Maybe you already have a data team, but it just hasn't been said. Folks supporting accounting and finance, folks writing SQL, making plots and charts and just generally wrangling data to provide value to the business.

Being clear with data goals and expectations can help accelerate the value that the data can provide. Daily updated dashboards can help a business understand where it is right now. Historical data analysis can help them see where they have been and forecasting can give a business an idea of where it might be in 6 months.

2022-02-18

Anti-Patterns in Experimentation

Anti-Patterns in Experimentation

Running experiments on websites involves showing 2 or more different experiences to similar but distinct groups of users and measuring the differences to determine which experience works best for the website. There are a variety of methods of setting up and running experiments and industry standards are unfortunately not yet clear.

Often experiments on websites start with a single developer putting in a single "if" statement and experimentation only grows from here.

The intent of this post is to highlight a few anti-patterns I've seen in the hopes that the next team implementing an experiment might avoid some of of the common pitfalls.

Here are the 3 most common anti-patterns in AB Testing that I've seen,

  1. Experimentation is a Library
  2. All Users are in all Experiments
  3. A pile of data dropped on an Analyst

Experimentation

At it's core experimentation is

  • Giving different experiences to different groups of users
  • Measuring differences
  • Moving forward with the experience that provides the best outcome

An experiment has to be implemented in a website, app or within the sending of emails. There also must be tracking of some sort to measure which experience each user was shown.

An Experiment Assignment is defined as a single user's experience and should include,

  • User id
  • Experiment Name
  • Variation Name
    • Which variation of the website did this user experience? For example, it could be the "red_button" or the "blue_button"
  • Timestamp
    • Ideally the first time the user encountered the experience.

Anti-Patterns

An anti-pattern is a pattern of code development or structure that seems like a good idea, but ultimately turns out poorly. When discussing software systems sometimes it's just as important to discuss best practices as to point out how things can go wrong.

Experimentation is a Library

Experimentation is a library! Call a function to split the users. Send the Experiment Assignments downstream for an analyst to use. No problem.

But wait, for the analyst, what does the data mean? how is it produced? where did it come from? why are we running this experiment at all?

All these questions should come out before the experiment is run to allow for methods and data to be aligned to generate the best outcome in an optimal manner.

Experimentation is a Process from hypothesis to development, analysis and cleanup and typically looks like,

  1. An experimenter hypothesizes that a new experience would be better by some measure
  2. An engineer develops the new experience to be able to run in parallel to the existing experience
  3. Users enter and interact with the 2+ experiences
  4. An analyst evaluates and compares the two experiences quantitatively
  5. An engineer codes the website to exclusively display the experience that is quantitatively better

Experimentation is a House of Cards that can return unusable or inaccurate results if any particular piece of this process fails to properly coordinate with the other pieces.

  1. The experimenter must have a reasonable hypothesis that can be quantitatively evaluate
  2. The engineer must properly, randomly split the users and present 2+ high quality experiences
  3. Users must be given time to enter and interact with the 2+ experiences
  4. The analyst must understand the data production and apply a rigorous analysis
  5. The engineer must prioritize and properly cleanup the codebase to guarantee that the best experience is shown to all users from now on

Any step can have minor bugs, but if there is a disconnect or any major bugs the whole system will topple. The experiment may produce incorrect results without anyone ever knowing that the results were incorrect.

Experimentation is NOT a library. It's a system, it's a process, it's a puzzle and the pieces must fit properly to provide high quality results.

All Users are in all Experiments

Every user that has ever landed on the website or that visits during an experiment gets an Experiment Assignment logged for the analyst to use.

Did they actually see the experiment? Who knows, doesn't matter, the analyst can figure it out.

😳

I have worked with outstanding analysts and am 100% positive they can figure this out and tease apart the raw data into some usable answers.

But how long will this take? How many experiments are we intending to run?

Analysts are busy and analytics takes time. Is it worth it to the business to have an analyst spending a week to produce an analysis for every experiment?

This pattern is easy on the Engineering team, but hard on an Analytics team. They will feel undeserved and unappreciated and will likely be overworked when asked to keep up with a high paced experimentation culture.

It also makes automation really hard as each test's analysis needs this extra bit of meta-data that may or may not capture the nuance of when the user actually saw the experiment.

Best to Devise a System of Data Logging that analysts can easily work with and that can allow for some automation.

A pile of data dropped on an Analyst

The old joke is that when you present a pile of data to a analyst and ask "What does this all mean?" the analyst will inevitably say "Not much". Pulling strong signals from experimentation requires up front planning from analysts. They can catch obvious bugs in the design, can point out metrics that can't be calculated and will recall existing similar experiments that have been run to help catch duplicate work.

Analysts are smart, hard working and resourceful. They will find some signal in whatever dataset they are presented with but it can be hard for an organization to measure and realize that they are spending an enormous amount of time generating conclusions from experimentation.

It's also impossible for an organization to measure the quality of a single experiment analysis. The system as a whole must be healthy for an organization to rely on the results.

Pull Analysts Into the Process Early to give your analysts some heads up and make sure they are part of the experiment process at the first step.

Conclusion

Avoiding some of the anti-patterns highlighted here will allow a team to move briskly into a future full of high quality, trusted experimentation.

Instead of Experimentation is a Library, recognize that Experimentation is a Process involving multiple teams and diverse points of view.

Instead of All Users are in all Experiments, work with analysts to Devise a System of Data Logging with experimentation in mind. Something that in intended for analysts to work with and will produce trusted experimentation results.

Instead of A pile of data dropped on an Analyst, Pull Analysts Into the Process Early. Work with your analysts to produce a system of experimentation easy to work with and trusted to produce quality results.

Go forth and keep trying new ideas that delight your users and help your website grow!

Further reading

I recommend the book "Trustworthy Online Controlled Experiments (A Practical Guide to A/B Testing)" by Ron Kohavi, Diane Tang and Ya Xu.

2022-01-10

Clean Code for Data Professionals

Simple Tips towards Clean Code for Data Folks

A few years ago I was a Software Engineer and my team lead asked me to take a look at a piece of code. This code interacted with a 3rd party library and we wanted to upgrade that library.

My team lead knew this code was quite old and understood that it might be hard to work with. He asked me to evaluate the level of effort to upgrade vs level of effort to re-write.

So I took a look and found a single C++ file

  • With a single class, with a single static function
    • With ~1200 lines of code
    • With dozens of local variables
    • With local variables reassigned 300 line after initially being set
  • With
    • no comments - literally 0, not one comment in the entire file
    • no unit tests
    • no tests of any sort

So I told my team lead that it would be easier to re-write the code than to refactor it. But anything could have tipped the balance back to refactor,

  • Comments would have helped to understand what was happening in the code
  • Tests would have allowed me to modify the code with confidence that I was maintaining the original functionality
  • Smaller functions would have helped increase the code readability
  • Constant local variables would have dramatically increased the readability of the code

Data professionals are not software engineers. Data Scientists and Data Analysts are definitely not, and Data Engineers are a mix as some come from data science and data analysis, and some from software engineering.

To that end, here are a few tips and tricks that should help make your code easier to read and maintain while still allowing the focus to be on the data and not the code.

Functions should fit on your Monitor

Top to bottom, all the code inside the function should fit on your screen. This drastically increases the readability of any particular piece of code as each function can be quickly read and understood.

This also applies to Jupyter notebooks and SQL statements. For example, I could remove all the section headers in this post, but that would make it a lot harder to read.

🔑 This is the main point here. All code becomes 10x easier to understood if it's chunked up into bite sized pieces.

Comments

At a minimum I would suggest

  • "Why does this file exist?" as a comment at the top of every file
  • "Why does this function/SQL exist?" as a comment for every function or SQL statement
  • "What are the data types of the arguments and the return value?" as a comment for every function in Python

Just remember, you will be picking up this code in ~6 months, and you can set yourself up for an easy reminder of what this code does, or a tough one.

Unit Tests

Any piece of code is tested by the developer. They run it through various scenarios with a range of data values. So it gets tested, but sometimes these tests don't get archived.

The time to formalize these tests and to put them into the codebase is small, but can save a tremendous amount of time at a later date.

Imagine picking up a piece of code that has 2-3 tests vs a piece of code with 0 tests? One is a lot easier and faster to pickup and modify.

Constant Local Variables

This can be really impactful for Jupyter Notebooks and for refactoring existing code.

For notebooks, with dozens of cells and variables, everything is a global variable and having confidence that variables are not in flux makes the code easier to read and maintain.

For refactoring, often data code ends up in large functions with dozens of local variables. Updating the variables to be unchanged or constant can make long functions easier to read and refactor.

Conclusion

These tips are for you. You will be the one working on your own code in 6 months, or someone on your team will go on to a new exciting opportunity, and you will be asked to work on their code.

Wouldn't you rather work on this code?

  • Short Functions
  • Comments
  • Unit Tests
  • Constant Local Variables